Skip to content

Commit d03d49e

Browse files
committed
Iterating on firebase cloud functions
1 parent d8da548 commit d03d49e

File tree

3 files changed

+1107
-28
lines changed

3 files changed

+1107
-28
lines changed

functions/index.js

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,25 @@
1-
// functions/src/index.ts (NO CHANGE - Admin SDK syntax is standard)
2-
3-
import * as functions from 'firebase-functions';
4-
import * as admin from 'firebase-admin';
1+
const {onValueCreated} = require("firebase-functions/v2/database");
2+
const admin = require('firebase-admin');
53

64
admin.initializeApp();
75
const db = admin.database();
8-
9-
// Cache for FCM tokens
106
const tokenCache = new Map();
117

12-
// Listen for new moves and send push notifications
13-
functions.database.ref('/moves')
14-
.onChildAdded(async (change, context) => {
15-
const move = change.after.val();
16-
console.log('New move:', move);
8+
exports.sendMoveNotification = onValueCreated('/moves/{moveId}', async (snapshot, context) => {
9+
const move = snapshot.val();
1710

1811
if (!move.friend) {
1912
console.log('No friend specified, skipping notification.');
2013
return null;
2114
}
2215

23-
// Check cache first
2416
let recipientToken = tokenCache.get(move.friend);
2517

26-
// If not in cache, fetch from database
2718
if (!recipientToken) {
2819
const recipientTokenSnapshot = await db.ref(`/users/${move.friend}/fcmToken`).once('value');
2920
recipientToken = recipientTokenSnapshot.val();
3021

3122
if (recipientToken) {
32-
// Cache the token
3323
tokenCache.set(move.friend, recipientToken);
3424
}
3525
}
@@ -44,13 +34,14 @@ functions.database.ref('/moves')
4434
title: `It's your turn!`,
4535
body: move.move,
4636
},
37+
token: fcmToken,
4738
data: {
4839
player: move.player,
4940
}
50-
};
41+
};
5142

5243
try {
53-
const response = await admin.messaging().sendToDevice(recipientToken, payload);
44+
const response = await admin.messaging().send(payload);
5445
console.log('Successfully sent message:', response);
5546

5647
if (response.results && response.results[0] && response.results[0].error) {

functions/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"name": "functions",
33
"description": "Cloud Functions for Firebase",
4+
"version": "0.0.1",
45
"scripts": {
56
"serve": "firebase emulators:start --only functions",
67
"shell": "firebase functions:shell",

0 commit comments

Comments
 (0)