MCPcopy
hub / github.com/dev-mastery/comments-api / makeCommentsDb

Function makeCommentsDb

src/data-access/comments-db.js:3–87  ·  view source on GitHub ↗
({ makeDb })

Source from the content-addressed store, hash-verified

1import Id from '../Id'
2
3export default function makeCommentsDb ({ makeDb }) {
4 return Object.freeze({
5 findAll,
6 findByHash,
7 findById,
8 findByPostId,
9 findReplies,
10 insert,
11 remove,
12 update
13 })
14 async function findAll ({ publishedOnly = true } = {}) {
15 const db = await makeDb()
16 const query = publishedOnly ? { published: true } : {}
17 const result = await db.collection('comments').find(query)
18 return (await result.toArray()).map(({ _id: id, ...found }) => ({
19 id,
20 ...found
21 }))
22 }
23 async function findById ({ id: _id }) {
24 const db = await makeDb()
25 const result = await db.collection('comments').find({ _id })
26 const found = await result.toArray()
27 if (found.length === 0) {
28 return null
29 }
30 const { _id: id, ...info } = found[0]
31 return { id, ...info }
32 }
33 async function findByPostId ({ postId, omitReplies = true }) {
34 const db = await makeDb()
35 const query = { postId: postId }
36 if (omitReplies) {
37 query.replyToId = null
38 }
39 const result = await db.collection('comments').find(query)
40 return (await result.toArray()).map(({ _id: id, ...found }) => ({
41 id,
42 ...found
43 }))
44 }
45 async function findReplies ({ commentId, publishedOnly = true }) {
46 const db = await makeDb()
47 const query = publishedOnly
48 ? { published: true, replyToId: commentId }
49 : { replyToId: commentId }
50 const result = await db.collection('comments').find(query)
51 return (await result.toArray()).map(({ _id: id, ...found }) => ({
52 id,
53 ...found
54 }))
55 }
56 async function insert ({ id: _id = Id.makeId(), ...commentInfo }) {
57 const db = await makeDb()
58 const result = await db
59 .collection('comments')
60 .insertOne({ _id, ...commentInfo })

Callers 6

index.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected