I have some thoughts on the article. However, I decided to enhance the commenting feature by allowing replies to comments.
Comment entity:
@Entity()
export class Comment {
@PrimaryColumn()
id: string;
@Column({ type: 'varchar', length: 50 })
content: string;
@Column()
authorId: string;
@Column()
entityId: string;
@CreateDateColumn()
createdAt: Date;
@Column('text', { nullable: true })
replyId?: string;
@Column({ type: 'enum', enum: CommentTypeEnum })
type: CommentTypeEnum;
}
Here are some specifics: When creating a reply to a comment, I capture the parent comment's id (the one being replied to) and store it in the replyId field. The parent comment can have NULL or another id as well; essentially, a new comment contains its parent's id.
[
{
"id": "dee96b97-cd45-4a09-a27d-985617cc5a16",
"content": "comment",
"authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
"entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
"createdAt": "2021-10-04T08:43:35.204Z",
"replyId": "cab2d3fd-7fba-4d02-a911-538246d92cfd",
"type": "COMMENT_TYPE"
},
...
]
Method used to fetch all records for a specific entity:
@Get('/:entityId/comments')
async getAll(@Param('entityId') entityId: string): Promise<CommentDto[]> {
const comments = await this.commentRepository.find({ where: { entityId: entityId }, order: { id: 'DESC' } });
return comments.map(it => ({
id: it.id,
content: it.content,
authorId: it.authorId,
entityId: it.entityId,
createdAt: it.createdAt,
replyId: it.replyId || null,
type: it.type,
}));
}
DTO:
export class CommentDto {
id: string;
content: string;
authorId: string;
entityId: string;
createdAt: Date;
replyId?: string;
type: CommentTypeEnum;
}
To retrieve records like the example below:
[
{
"id": "4f7b2bb3-b224-45d9-8093-9c0de7514bd4",
"content": "comment",
"authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
"entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
"createdAt": "2021-10-04T08:43:04.391Z",
"replyId": [
{
"id": "cab2d3fd-7fba-4d02-a911-538246d92cfd",
"content": "comment",
"authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
"entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
"createdAt": "2021-10-04T08:43:22.663Z",
"replyId": [...],
"type": "COMMENT_TYPE"
},
...
],
"type": "COMMENT_TYPE"
}
]
Thank you in advance for your response