-
Notifications
You must be signed in to change notification settings - Fork 0
/
pageUtils.ts
89 lines (76 loc) · 2.57 KB
/
pageUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { firestoreAdmin } from "~/server/firebase/firebaseAdmin";
import {
Comment,
CreateCommentRequest,
CreatePageRequest,
UpdateCommentRequest,
UpdatePageRequest,
} from "~/types/server";
import { deleteCollection } from "./firestoreUtils";
const PAGES_COLLECTION = firestoreAdmin.collection("pages");
/**
* Gets the reference to the comment subcollection of a page.
*
* @param pageId The page's id
* @returns The reference to the `comments` subcollection.
*/
function getCommentsCollection(pageId: string) {
return PAGES_COLLECTION.doc(pageId).collection("comments");
}
///////////
// PAGES //
///////////
export async function getPageById(pageId: string) {
const result = await PAGES_COLLECTION.doc(pageId).get();
if (!result.exists) {
throw Error("No such page!");
}
// Get all comment in the page as well.
const comments: Comment[] = (await getCommentsCollection(pageId)
.get()
.then(query => query.docs.map(doc => doc.data()))) as Comment[];
return {
...result,
approvedComments: comments.filter(c => c.status === "Approved"),
pendingApprovedComments: comments.filter(c => c.status === "Pending"),
};
}
export async function createPage(data: CreatePageRequest) {
const pageRef = data.id ? PAGES_COLLECTION.doc(data.id) : PAGES_COLLECTION.doc();
return await pageRef.create({ id: pageRef.id, ...data });
}
export async function updatePageById(pageId: string, data: UpdatePageRequest) {
return await PAGES_COLLECTION.doc(pageId).update(data);
}
export async function deletePageById(pageId: string) {
const pageRef = PAGES_COLLECTION.doc(pageId);
await deleteCollection(getCommentsCollection(pageId));
return await pageRef.delete();
}
//////////////
// COMMENTS //
//////////////
/**
* Creates a new comment for a particular page.
* @param pageId The page's id
* @param data The data of the comment
*/
export async function createPageComment(pageId: string, data: CreateCommentRequest) {
const commentRef = getCommentsCollection(pageId).doc();
return await commentRef.create({ id: commentRef.id, ...data });
}
export async function updatePageCommentById(
pageId: string,
commentId: string,
data: UpdateCommentRequest
) {
return await getCommentsCollection(pageId).doc(commentId).update(data);
}
/**
* Delete a particular comment
* @param pageId The page's id
* @param commentId The comment's id
*/
export async function deletePageCommentById(pageId: string, commentId: string) {
return await getCommentsCollection(pageId).doc(commentId).delete();
}