Skip to content

Commit

Permalink
updated replies api
Browse files Browse the repository at this point in the history
  • Loading branch information
tigransimonyan committed Mar 10, 2024
1 parent 7a3328f commit bab3c53
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
22 changes: 20 additions & 2 deletions src/api/comments/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ export const add = asyncRoute(async (req, res) => {
const url = new URL(req.body.pageUrl);
const email = req.body.email || req.body?.owner.email || '';
const author = req.body.author || req.body?.owner.name || '';
const parentId = req.body.parentId;
const domain = url.hostname;
const gravatar = crypto.createHash('md5').update(email).digest('hex');

const data = {
body: req.body.body,
// owner field deprecated
owner: { name: author, email, gravatar },
parentId,
gravatar,
author,
email,
Expand All @@ -40,7 +42,9 @@ export const add = asyncRoute(async (req, res) => {
});

export const list = asyncRoute(async (req, res) => {
const query: any = {};
const query: any = {
parentId: null
};

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

res.json(comments);
const commentsWithReplies = await Promise.all(
comments.map(comment => {
return Comment.find({ parentId: comment.id })
.select('owner.name owner.gravatar body createdAt gravatar author parentId')
.sort({ createdAt: 'asc' })
.then(replies => {
return {
...comment.toObject(),
replies
};
});
})
);

res.json(commentsWithReplies);
});

export const remove = asyncRoute(async (req, res) => {
Expand Down
3 changes: 2 additions & 1 deletion src/api/comments/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const schema = new Schema<TComment>(
},
parentId: {
type: String,
required: false
required: false,
ref: 'Comment'
},
gravatar: {
type: String,
Expand Down

0 comments on commit bab3c53

Please sign in to comment.