Firebase Cloud Functionを以下のサイトで勉強しています。
https://codelabs.developers.google.com/codelabs/firebase-cloud-functions/#9
チュートリアルにあるコード
javascript
1// Import the Firebase SDK for Google Cloud Functions. 2const functions = require('firebase-functions'); 3// Import and initialize the Firebase Admin SDK. 4const admin = require('firebase-admin'); 5admin.initializeApp(); 6 7// Sends a notifications to all users when a new message is posted. 8exports.sendNotifications = functions.database.ref('/messages/{messageId}').onCreate( 9 async (snapshot) => { 10 // Notification details. 11 const text = snapshot.val().text; 12 const payload = { 13 notification: { 14 title: `${snapshot.val().name} posted ${text ? 'a message' : 'an image'}`, 15 body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', 16 icon: snapshot.val().photoUrl || '/images/profile_placeholder.png', 17 click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`, 18 } 19 }; 20 21 // Get the list of device tokens. 22 const allTokens = await admin.database().ref('fcmTokens').once('value'); 23 if (allTokens.exists()) { 24 // Listing all device tokens to send a notification to. 25 const tokens = Object.keys(allTokens.val()); 26 27 // Send notifications to all tokens. 28 const response = await admin.messaging().sendToDevice(tokens, payload); 29 await cleanupTokens(response, tokens); 30 console.log('Notifications have been sent and tokens cleaned up.'); 31 } 32 });
の最後の部分を以下のように変更したところ、タイトルのエラーが出ました。
javascript
1// Sends a notifications to all users when a new message is posted. 2exports.sendNotifications = functions.database.ref('/messages/{messageId}').onCreate( 3 async (snapshot) => { 4 // Notification details. 5 const text = snapshot.val().text; 6 const payload = { 7 notification: { 8 title: `${snapshot.val().name} posted ${text ? 'a message' : 'an image'}`, 9 body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', 10 icon: snapshot.val().photoUrl || '/images/profile_placeholder.png', 11 click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`, 12 } 13 }; 14 15 terminateNotification(); 16 17 }); 18 19function terminateNotification() { 20 // get list of device tokens 21 const allTokens = await admin.database().ref('fcmTokens').once('value'); 22 if (allTokens.exists()) { 23 // listing all tokens to send notification 24 const tokens = Object.keys(allTokens.val()); 25 26 // send notification to all tokens 27 const response = await admin.messaging().sendToDevice(tokens, payload); 28 await cleanupTokens(response, tokens); 29 console.log('notifications sent & tokens cleand up'); 30 } 31}
adminはコードの最初に宣言しているのに、なぜ関数化するとunexpeted tokenになるのかわかりません。
あなたの回答
tips
プレビュー