| 1 | export 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 | } |