This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
CloudFunctions.js
75 lines (62 loc) · 2.63 KB
/
CloudFunctions.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
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp ({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://your-database-URL.firebaseio.com'
});
exports.fetchContacts = functions.https.onRequest((request, response) => {
const preparedNumbers = request.body.data.preparedNumbers;
var users = [];
Promise.all(preparedNumbers.map(preparedNumber => {
return admin.database().ref('/users').orderByChild("phoneNumber").equalTo(preparedNumber).once('value').then(snapshot => {
if (snapshot.exists()) {
snapshot.forEach((childSnap) => {
const uid = childSnap.key;
var userData = childSnap.val();
userData.id = uid;
users.push(userData);
})
}
})
})).then(() => {
return Promise.all([response.send({data: users})]);
});
});
exports.sendGroupMessage = functions.database.ref('/groupChats/{chatID}/userMessages/{messageID}').onCreate((snap, context) => {
const chatID = context.params.chatID;
const messageID = context.params.messageID;
var lastMessageID = "";
const senderID = snap.val();
return admin.database().ref(`/groupChats/${chatID}/userMessages`).orderByKey().limitToLast(1).once('child_added').then(snapshot => {
lastMessageID = snapshot.key;
admin.database().ref(`/groupChats/${chatID}/metaData/chatParticipantsIDs`).once('value').then(snapshot => {
let members = Object.keys(snapshot.val());
members.forEach(function(memberID) {
if (memberID != senderID) {
sendMessageToMember(memberID);
incrementBadge(memberID);
updateChatLastMessage(memberID);
}
});
});
});
function sendMessageToMember(memberID) {
let userMessagesReference = admin.database().ref(`/user-messages/${memberID}/${chatID}/userMessages`)
userMessagesReference.update({
[messageID] : senderID
});
}
function updateChatLastMessage(memberID) {
let userMessagesReference = admin.database().ref(`/user-messages/${memberID}/${chatID}/metaData`)
userMessagesReference.update({
"lastMessageID": lastMessageID
});
}
function incrementBadge(memberID) {
let badgeReference = admin.database().ref(`/user-messages/${memberID}/${chatID}/metaData/badge`)
badgeReference.transaction(function (currentValue) {
return (currentValue || 0) + 1;
});
}
});