Skip to content

Commit 8bd39c7

Browse files
Added lastMessage function to examples (#16)
* Added lastMessage function to examples (Tested, it works :D) * fixed function overriding old room fields .set() overrode old room fields which broke everything. I fixed this issue in this commit. * Update firebase-cloud-functions.md
1 parent ba6d76c commit 8bd39c7

File tree

1 file changed

+42
-18
lines changed

1 file changed

+42
-18
lines changed

doc/firebase-cloud-functions.md

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,53 @@ title: Cloud Functions
55

66
This is an example of a cloud function that sets a message's status to delivered once the message is received on Firebase.
77

8-
```ts
9-
import * as functions from 'firebase-functions'
10-
11-
export const changeMessageStatus = functions.firestore
12-
.document('rooms/{roomId}/messages/{messageId}')
13-
.onWrite((change) => {
14-
const message = change.after.data()
15-
if (message) {
16-
if (['delivered', 'read'].includes(message.status)) {
17-
return null
8+
```js
9+
const functions = require("firebase-functions");
10+
11+
exports.changeMessageStatus = functions.firestore
12+
.document("rooms/{roomId}/messages/{messageId}")
13+
.onWrite((change) => {
14+
const message = change.after.data();
15+
if (message) {
16+
if (["delivered", "read"].includes(message.status)) {
17+
return null;
18+
} else {
19+
return change.after.ref.update({
20+
status: "delivered",
21+
});
22+
}
23+
} else {
24+
return null;
25+
}
26+
});
27+
```
28+
29+
This is an example of a cloud function that sets a room's `lastMessage` to the most recent message sent once recieved in Firestore.
30+
31+
```js
32+
const functions = require("firebase-functions");
33+
const admin = require("firebase-admin");
34+
35+
admin.initializeApp();
36+
37+
const db = admin.firestore();
38+
39+
exports.changeLastMessage = functions.firestore
40+
.document("rooms/{roomId}/messages/{messageId}")
41+
.onUpdate((change, context) => {
42+
const message = change.after.data();
43+
if (message) {
44+
return db.doc("rooms/" + context.params.roomId).update({
45+
lastMessage: message,
46+
});
1847
} else {
19-
return change.after.ref.update({
20-
status: 'delivered',
21-
})
48+
return null;
2249
}
23-
} else {
24-
return null
25-
}
26-
})
50+
});
2751
```
2852

2953
:::important
3054

31-
This function was created using a deprecated Node 8 environment on a free Firebase plan. Starting from March 15, 2021, you will need a paid plan to use Cloud Functions, so there might be a better way to do it. We will explore options to create more examples, including `read` status and push notifications.
55+
Starting from March 15, 2021, you will need a paid plan to use Cloud Functions, so there might be a better way to do it. We will explore options to create more examples, including `read` status and push notifications.
3256

3357
:::

0 commit comments

Comments
 (0)