Firebase Cloud Function代码需求:根据用户反应更新字段
Hey there! Let's tackle this Firebase Cloud Function requirement. You want to automatically set CurrentUserReaction to "true" whenever the logged-in user's ID exists in the UsersWhoReacted node of a post, right? Here's a practical, step-by-step solution:
First, make sure you have the Firebase CLI set up and your project initialized. Then, create a function that listens for changes to the UsersWhoReacted node to keep the reaction status in sync.
Full Function Code
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); // Trigger when a user's reaction is added or removed from a post exports.syncUserReaction = functions.database.ref('/Posts/{postId}/UsersWhoReacted/{userId}') .onWrite(async (change, context) => { // Extract post ID and user ID from the trigger context const postId = context.params.postId; const userId = context.params.userId; // Check if the user's reaction was added (not removed) const isReactionAdded = change.after.exists(); // Get reference to the parent post node const postRef = admin.database().ref(`/Posts/${postId}`); if (isReactionAdded) { // If user added their reaction, set CurrentUserReaction to "true" await postRef.update({ CurrentUserReaction: "true" }); functions.logger.info(`Updated reaction status to true for post ${postId} (user: ${userId})`); } else { // If user removed their reaction, set CurrentUserReaction to "false" await postRef.update({ CurrentUserReaction: "false" }); functions.logger.info(`Updated reaction status to false for post ${postId} (user: ${userId})`); } return null; });
Key Details Explained
- Trigger Path: The function listens to
/Posts/{postId}/UsersWhoReacted/{userId}so it fires every time a user's ID is added to or removed from the reactions list. - Context Params:
context.paramsgives us direct access to the post ID and user ID involved in the change, so we don't have to parse paths manually. - Reaction Check:
change.after.exists()tells us if the user's ID was just added (true) or removed (false). - Admin SDK: We use the Firebase Admin SDK to update the
CurrentUserReactionfield—this gives the function full permissions to modify your Realtime Database (ensure your service account has the necessary access).
How to Deploy
Run this command in your project directory to deploy the function:
firebase deploy --only functions:syncUserReaction
Optional Adjustment
If you want CurrentUserReaction to only be "false" when no users have reacted at all (not just when the current user removed their reaction), you can add a quick check before updating:
// Inside the else block const reactionsSnapshot = await postRef.child('UsersWhoReacted').once('value'); const hasAnyReactions = reactionsSnapshot.exists(); await postRef.update({ CurrentUserReaction: hasAnyReactions ? "true" : "false" });
But based on your original requirement, the first version should be exactly what you need.
内容的提问来源于stack exchange,提问作者Hacker10

