For my upcoming blog project, I am implementing a feature where users can like comments or posts using TypeORM with PostgreSQL. Below is the entity structure for likes:
@Entity()
@Unique(["user", "post", "comment"])
export default class Like {
@PrimaryGeneratedColumn()
id: number;
// @Column()
// likeCount: number;
@ManyToOne(() => User, (user) => user.likes, { nullable: false })
user: User;
@ManyToOne(() => Post, (post) => post.likes)
post: Post;
@ManyToOne(() => Comment, (comment) => comment.likes)
comment: Comment;
I am facing an issue where I need to prevent a user from liking a comment/post more than once. The unique constraints in the code above are not achieving this. Should I consider creating separate tables for liking a post and liking a comment? Also, how can I track the total number of likes for each comment/post?
The current unique constraint setup is ineffective and needs an alternative approach.