Skip to content

Commit bab3c53

Browse files
updated replies api
1 parent 7a3328f commit bab3c53

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/api/comments/controller.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ export const add = asyncRoute(async (req, res) => {
1010
const url = new URL(req.body.pageUrl);
1111
const email = req.body.email || req.body?.owner.email || '';
1212
const author = req.body.author || req.body?.owner.name || '';
13+
const parentId = req.body.parentId;
1314
const domain = url.hostname;
1415
const gravatar = crypto.createHash('md5').update(email).digest('hex');
1516

1617
const data = {
1718
body: req.body.body,
1819
// owner field deprecated
1920
owner: { name: author, email, gravatar },
21+
parentId,
2022
gravatar,
2123
author,
2224
email,
@@ -40,7 +42,9 @@ export const add = asyncRoute(async (req, res) => {
4042
});
4143

4244
export const list = asyncRoute(async (req, res) => {
43-
const query: any = {};
45+
const query: any = {
46+
parentId: null
47+
};
4448

4549
if (req.query.pageId) {
4650
query.pageId = req.query.pageId;
@@ -52,7 +56,21 @@ export const list = asyncRoute(async (req, res) => {
5256
.select('owner.name owner.gravatar body createdAt gravatar author')
5357
.sort({ createdAt: 'asc' });
5458

55-
res.json(comments);
59+
const commentsWithReplies = await Promise.all(
60+
comments.map(comment => {
61+
return Comment.find({ parentId: comment.id })
62+
.select('owner.name owner.gravatar body createdAt gravatar author parentId')
63+
.sort({ createdAt: 'asc' })
64+
.then(replies => {
65+
return {
66+
...comment.toObject(),
67+
replies
68+
};
69+
});
70+
})
71+
);
72+
73+
res.json(commentsWithReplies);
5674
});
5775

5876
export const remove = asyncRoute(async (req, res) => {

src/api/comments/model.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ const schema = new Schema<TComment>(
2424
},
2525
parentId: {
2626
type: String,
27-
required: false
27+
required: false,
28+
ref: 'Comment'
2829
},
2930
gravatar: {
3031
type: String,

0 commit comments

Comments
 (0)