add relations

This commit is contained in:
Ken Yasue
2025-06-01 22:36:04 +02:00
parent 5149012dcf
commit 8671a058be
7 changed files with 476 additions and 20 deletions

View File

@ -0,0 +1,34 @@
import { Column, Entity, ManyToOne, ManyToMany, JoinColumn, JoinTable, type Relation } from "typeorm"
import { UserEntity } from "./UserEntity"
import { TagEntity } from "./TagEntity"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
@Entity({ name: "posts" })
export class PostEntity extends AbstractBaseEntity {
@Column({ type: "text" })
content!: string
@Column({ type: "varchar" })
userEmail!: string
@Column({ type: "varchar" })
username!: string
@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
createdAt!: Date
@ManyToOne(() => UserEntity, { nullable: true })
@JoinColumn({ name: "userEmail", referencedColumnName: "email" })
user!: Relation<UserEntity> | null
@ManyToMany(() => TagEntity, (tag) => tag.posts)
@JoinTable({
name: "post_tags",
joinColumn: { name: "postId", referencedColumnName: "id" },
inverseJoinColumn: { name: "tagId", referencedColumnName: "id" }
})
tags!: TagEntity[]
}
export default PostEntity

View File

@ -0,0 +1,18 @@
import { Column, Entity, ManyToMany } from "typeorm"
import { PostEntity } from "./PostEntity"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
@Entity({ name: "tags" })
export class TagEntity extends AbstractBaseEntity {
@Column({ type: "varchar", unique: true })
name!: string
@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
createdAt!: Date
@ManyToMany(() => PostEntity, (post) => post.tags)
posts!: PostEntity[]
}
export default TagEntity

View File

@ -3,9 +3,10 @@ import SessionEntity from "./SessionEntity"
import AccountEntity from "./AccountEntity"
import { transformer } from "../utils/transformers"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
import { PostEntity } from "./PostEntity"
@Entity({ name: "users" })
export class UserEntity extends AbstractBaseEntity {
export class UserEntity extends AbstractBaseEntity {
@Column({ type: "varchar", nullable: true })
name!: string | null
@ -30,4 +31,7 @@ export class UserEntity extends AbstractBaseEntity {
@OneToMany(() => AccountEntity, (account) => account.userId)
accounts!: Relation<AccountEntity>[]
}
@OneToMany(() => PostEntity, (post) => post.user)
posts!: Relation<PostEntity>[]
}

View File

@ -1,17 +1,21 @@
"use node"
import { dataSource } from "./data-source";
import { UserEntity } from "./entity/UserEntity";
import { PostEntity } from "./entity/PostEntity";
import { TagEntity } from "./entity/TagEntity";
let dbInstance = dataSource;
// you can add a try catch
export const dbSource = async () => {
if(!dataSource.isInitialized) {
if (!dataSource.isInitialized) {
dbInstance = await dataSource.initialize();
}
return {
userRepository: dbInstance.getRepository(UserEntity),
postRepository: dbInstance.getRepository(PostEntity),
tagRepository: dbInstance.getRepository(TagEntity),
}
}
}