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
64admin . initializeApp ( ) ;
75const db = admin . database ( ) ;
8-
9- // Cache for FCM tokens
106const 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 ) {
0 commit comments