如何通过Cloud Function在Firebase实时数据库Message节点新增子节点时推送通知?
Hey there! I've got you covered with a complete Cloud Function setup to handle this push notification requirement. Since you're new to Node.js, I'll break it down step by step and explain each part clearly so you can follow along easily.
Before diving into code, make sure you have these setup:
- Install the Firebase CLI: Run
npm install -g firebase-toolsin your terminal - Initialize Cloud Functions in your Firebase project: Execute
firebase init functionsand follow the prompts (choose JavaScript as the language) - Enable Firebase Cloud Messaging (FCM) in your Firebase Console (it's usually enabled by default, but double-check under the "Cloud Messaging" tab)
Replace the contents of functions/index.js with this code:
const functions = require("firebase-functions"); const admin = require("firebase-admin"); // Initialize Firebase Admin SDK admin.initializeApp(); // Trigger this function when a new message is added to the /Message node exports.sendNewMessageNotification = functions.database .ref("/Message/{messageId}") .onCreate(async (snapshot, context) => { try { // 1. Fetch all user FCM tokens from your database // Adjust the path below to match where you store user data (e.g., /users/{userId}/fcmToken) const usersSnapshot = await admin.database().ref("/users").once("value"); const users = usersSnapshot.val(); if (!users) { functions.logger.info("No users found to send notifications to"); return null; } // Collect all valid FCM tokens (filter out any empty/null tokens) const fcmTokens = Object.values(users) .map(user => user.fcmToken) .filter(token => token !== null && token !== undefined); if (fcmTokens.length === 0) { functions.logger.info("No valid FCM tokens found"); return null; } // 2. Create the notification payload const notificationPayload = { notification: { title: "New Message Alert", body: "You have new message" } }; // 3. Send the notification to all users const response = await admin.messaging().sendMulticast({ tokens: fcmTokens, notification: notificationPayload.notification }); // Log results functions.logger.info(`Successfully sent ${response.successCount} notifications`); functions.logger.warn(`Failed to send ${response.failureCount} notifications`); // Optional: Handle failed tokens (you could remove invalid tokens from your database here) const failedTokens = []; response.responses.forEach((resp, idx) => { if (!resp.success) { failedTokens.push(fcmTokens[idx]); } }); if (failedTokens.length > 0) { functions.logger.error("Failed tokens:", failedTokens); } return null; } catch (error) { functions.logger.error("Error sending notifications:", error); return null; } });
- Database Paths: The code assumes you store user data in
/userswith each user having anfcmTokenfield. If your structure is different (e.g.,/userProfiles/{userId}/deviceToken), update the path inadmin.database().ref("/users")and theuser.fcmTokenpart. - Notification Content: You can tweak the
titleandbodyin thenotificationPayloadif you want to adjust the notification text.
Once you've adjusted the code to match your project, run this command in your terminal (from the functions directory or your project root):
firebase deploy --only functions
That's it! Now whenever a new child node is added to /Message, the function will trigger and send the notification to all users with valid FCM tokens stored in your database.
内容的提问来源于stack exchange,提问作者Sairaj

