如何在Firebase云函数中实现评论、点赞等不同类型的设备通知?
Hey there! You’ve already nailed the follow notification functionality—awesome work! Let’s expand that code to handle likes and comments too. The core idea is to add a notification type field to your database entries, then use that to dynamically generate the right notification content in your cloud function. Here’s how to do it:
Step 1: Update Your Notification Data Structure
First, when you write a notification to /notification/{user_id}/{notification_id} from your frontend, add a type field to specify what kind of notification it is. For example:
- For a follow:
{ from: "user123", message: "", type: "follow" } - For a like:
{ from: "user123", message: "liked your post", type: "like" } - For a comment:
{ from: "user123", message: "Great post!", type: "comment" }
Step 2: Modify the Cloud Function to Handle Different Types
We’ll adjust your existing function to read the type field, then generate the appropriate notification title and body based on that type. Here’s the updated code:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendNotification = functions.database.ref('/notification/{user_id}/{notification_id}') .onWrite(async (change, context) => { // Skip if the notification is being deleted if (!change.after.exists()) { return console.log('Notification deleted, no action needed'); } const user_id = context.params.user_id; const notification_id = context.params.notification_id; console.log('Preparing to send notification to user:', user_id); // Fetch the notification data const notificationSnapshot = await admin.database() .ref(`/notification/${user_id}/${notification_id}`) .once('value'); const notificationData = notificationSnapshot.val(); const from_user_id = notificationData.from; const notificationType = notificationData.type; const customMessage = notificationData.message; console.log('Notification type:', notificationType, 'from user:', from_user_id); // Fetch the sender's username and recipient's device token const [userSnapshot, tokenSnapshot] = await Promise.all([ admin.database().ref(`users/${from_user_id}/username`).once('value'), admin.database().ref(`users/${user_id}/device_token`).once('value') ]); const userName = userSnapshot.val(); const token_id = tokenSnapshot.val(); if (!token_id) { return console.log('No device token found for user:', user_id); } // Dynamically build the notification payload based on type let payload; switch(notificationType) { case 'follow': payload = { notification: { title: "Someone is following you!", body: `${userName} started following you`, icon: "default", click_action: "alpha.noname_TARGET_NOTFICATION" }, data: { from_user_id: from_user_id, type: 'follow' } }; break; case 'like': payload = { notification: { title: "Your post was liked!", body: `${userName} ${customMessage}`, icon: "default", click_action: "alpha.noname_TARGET_NOTFICATION" }, data: { from_user_id: from_user_id, type: 'like' } }; break; case 'comment': payload = { notification: { title: "New comment on your post!", body: `${userName}: ${customMessage}`, icon: "default", click_action: "alpha.noname_TARGET_NOTFICATION" }, data: { from_user_id: from_user_id, type: 'comment' } }; break; default: return console.log('Unknown notification type:', notificationType); } // Send the notification try { const response = await admin.messaging().sendToDevice(token_id, payload); console.log('Notification sent successfully:', response); // Optional: Delete the notification after sending (if you don't need to keep it) await admin.database().ref(`/notification/${user_id}/${notification_id}`).remove(); return true; } catch (error) { console.error('Error sending notification:', error); return false; } });
Key Improvements in This Code:
- Async/Await Syntax: Makes the code cleaner and easier to read compared to nested
.then()calls. - Notification Type Handling: Uses a
switchstatement to generate the right payload for each notification type. - Error Checks: Skips deleted notifications, checks for missing device tokens, and handles unknown types.
- Data Field: Adds the
typeto the notification data, so your app can handle the click action appropriately (e.g., open the post that was liked/commented on).
Quick Notes:
- Make sure your frontend writes the correct
typevalue when creating each notification. - You can customize the
titleandbodytext to match your app’s tone. - The optional step to delete the notification after sending keeps your database clean—remove that line if you want to retain notifications for a feed.
内容的提问来源于stack exchange,提问作者user9822291

