I am trying to have a calculated field which will basically check if a related table contains a particular row. To be exact, I have a Post entity which has author as a relation (ManyToOne) to User entity; I have a query to get a single post by id, and I also want to add a field in the return Post object i.e. if the particular post is liked by me.
Post Entity - Post.ts
@Entity()
export class Post extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string
@ManyToOne(() => User, (user) => user.posts, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'author_id' })
author: User
@OneToMany(() => Like, (like) => like.post)
likes: Like[]
// ... other columns
}
User Entity - User.ts
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string
@OneToMany(() => Post, (post) => post.author)
posts: Post[]
@OneToMany(() => Like, (like) => like.author)
likes: Like[]
// ... other columns
}
Like Entity - Like.ts
@Entity()
export class Like extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string
@ManyToOne(() => Post, (post) => post.likes, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'post_id' })
post: Post
@ManyToOne(() => User, (user) => user.likes, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'author_id' })
author: User
// ... other columns
}
Get Post Controller - /post/[id].ts
export const get = async (req: Request, res: Response, next: NextFunction) => {
const { id } = req.params
const { user_id } = req // simplified version of JWT token
const postRepository = db.getRepository(Post)
const post = await postRepository
.createQueryBuilder('post')
.where('post.id = :id', { id })
.leftJoinAndSelect('post.author', 'author')
.getOne()
// here I want a field called 'likedByMe'
// ... other logic
}
The above end point return this (simplified):
{
"id": "...",
"created_at": "2022-05-28T20:05:54.060Z",
"updated_at": "2022-05-29T15:18:17.525Z",
"content": "<p>...</p>\n",
"author": {
"id": "...",
"username": "john",
"name": "John Doe",
"avatar": "https://....cloudfront.net"
},
I need to add a field called isLikedByMe in the response which will return a boolean value.
Any help is really appreciated! I am sorry if I have used any wrong terminology, I am pretty new to TypeORM or any complicated queries. Thank you