Skip to content

Commit 18114bd

Browse files
committed
Refactor CommentsRepository and CommentsService for enhanced comment retrieval
- Add a new method in CommentsRepository to find comments by article ID, optimized to include author details and their followers. - Simplify comment mapping in CommentsService to directly include author information, greatly improving performance from O(n*(k+t)) to O(n).
1 parent f8e7faa commit 18114bd

File tree

2 files changed

+36
-20
lines changed

2 files changed

+36
-20
lines changed

src/articles/comments/comments.repository.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import { and, desc, eq } from 'drizzle-orm';
2-
31
import type { Database } from '@/database.providers';
42
import { articles, comments } from '@articles/articles.model';
3+
import { and, desc, eq } from 'drizzle-orm';
54
import type { CommentToCreate } from './comments.schema';
65

76
export class CommentsRepository {
@@ -35,10 +34,31 @@ export class CommentsRepository {
3534
return result;
3635
}
3736

37+
/**
38+
* Find all comments by article id
39+
*
40+
* Note: this operation is optimized to include the author and their followers.
41+
* Use it with caution. If you need something simpler, consider refactoring this method and making the "with" option dynamic.
42+
* @param articleId - The id of the article
43+
* @returns An array of comments
44+
*/
3845
async findManyByArticleId(articleId: number) {
3946
const result = await this.db.query.comments.findMany({
4047
where: eq(comments.articleId, articleId),
4148
orderBy: [desc(comments.createdAt)],
49+
with: {
50+
author: {
51+
columns: {
52+
id: true,
53+
username: true,
54+
bio: true,
55+
image: true,
56+
},
57+
with: {
58+
followers: true,
59+
},
60+
},
61+
},
4262
});
4363
return result;
4464
}

src/articles/comments/comments.service.ts

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -63,24 +63,20 @@ export class CommentsService {
6363
article.id,
6464
);
6565

66-
const returnedComments = await Promise.all(
67-
comments.map(async (comment) => {
68-
const authorProfile = await this.profilesService.findByUserId(
69-
currentUserId ?? null,
70-
comment.authorId,
71-
);
72-
73-
return {
74-
id: comment.id,
75-
body: comment.body,
76-
createdAt: comment.createdAt,
77-
updatedAt: comment.updatedAt,
78-
author: authorProfile.profile,
79-
};
80-
}),
81-
);
82-
83-
return returnedComments;
66+
return comments.map((comment) => ({
67+
id: comment.id,
68+
body: comment.body,
69+
createdAt: comment.createdAt,
70+
updatedAt: comment.updatedAt,
71+
author: {
72+
username: comment.author.username,
73+
bio: comment.author.bio,
74+
image: comment.author.image,
75+
following: currentUserId
76+
? comment.author.followers.some((f) => f.followerId === currentUserId)
77+
: false,
78+
},
79+
}));
8480
}
8581

8682
async deleteComment(

0 commit comments

Comments
 (0)