-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdatePost.js
90 lines (76 loc) · 2.37 KB
/
updatePost.js
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
90
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const marked = require("marked");
/**
* Update (or delete) post if room creator, initializator or post author.
*/
exports.updatePost = functions.https.onCall(
async ({ roomId, postId, text, forceDelete }, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
"unauthenticated",
"The function must be called while authenticated."
);
}
if (!roomId) {
throw new functions.https.HttpsError(
"invalid-argument",
"The function must be called with a valid roomId."
);
}
if (!postId) {
throw new functions.https.HttpsError(
"invalid-argument",
"The function must be called with a valid postId."
);
}
const room = await admin.firestore().collection("rooms").doc(roomId).get();
const isRoomManager = [
room.get("creatorId"),
room.get("initializatorId"),
].includes(context.auth.uid);
if (!room.exists) {
throw new functions.https.HttpsError(
"not-found",
"The room does not exist."
);
}
const db = admin.firestore();
const ref = db.doc(`rooms/${roomId}/posts/${postId}`);
const uref = db.doc(`users/${context.auth.uid}/posts/${postId}`);
return db.runTransaction(async (transaction) => {
const doc = await transaction.get(ref);
const udoc = await transaction.get(uref);
if (!doc.exists) {
throw new functions.https.HttpsError(
"not-found",
"The post does not exist."
);
}
if (!udoc.exists && !isRoomManager) {
throw new functions.https.HttpsError(
"permission-denied",
"Zamítám. Nejste autorem, ani správcem místnosti."
);
}
const updatedAt = admin.firestore.FieldValue.serverTimestamp();
const post = {
text,
html: marked.parse(text),
updatedAt,
};
if (!text && forceDelete) {
await transaction.delete(ref);
} else {
await transaction.update(ref, post);
}
// once room manager edits a post, we need to create new post under the manager's user collection
await transaction[udoc.exists ? "update" : "create"](uref, {
roomId,
postId,
updatedAt,
});
return { id: postId, ...post };
});
}
);