MCPcopy Index your code
hub / github.com/dev-mastery/comments-api / makeListComments

Function makeListComments

src/use-cases/list-comments.js:1–30  ·  view source on GitHub ↗
({ commentsDb })

Source from the content-addressed store, hash-verified

1export default function makeListComments ({ commentsDb }) {
2 return async function listComments ({ postId } = {}) {
3 if (!postId) {
4 throw new Error('You must supply a post id.')
5 }
6 const comments = await commentsDb.findByPostId({
7 postId,
8 omitReplies: false
9 })
10 const nestedComments = nest(comments)
11 return nestedComments
12
13 // If this gets slow introduce caching.
14 function nest (comments) {
15 if (comments.length === 0) {
16 return comments
17 }
18 return comments.reduce((nested, comment) => {
19 comment.replies = comments.filter(
20 reply => reply.replyToId === comment.id
21 )
22 nest(comment.replies)
23 if (comment.replyToId == null) {
24 nested.push(comment)
25 }
26 return nested
27 }, [])
28 }
29 }
30}

Callers 1

index.jsFile · 0.85

Calls 1

nestFunction · 0.85

Tested by

no test coverage detected