如何在OnCreate中获取快照父引用的值?

时间:2019-04-05 09:56:18

标签: firebase google-cloud-functions

我试图使用Firebase实时数据库触发器在OnCreate中获取快照父引用的值,然后将该值传递给admin SDK,以从实时数据库中读取一些值。

我似乎无法从快照父引用中获取值。

我不熟悉云功能,请为此提供帮助。谢谢

'use strict';

        const functions = require('firebase-functions');

        // The Firebase Admin SDK to access the Firebase Realtime Database
        const admin = require('firebase-admin');
        admin.initializeApp();

        exports.sendLikeNotification = functions.database.instance('linkmobileapp-business').ref('/articles/{articleCategory}/{articleKey}/stars/{userId}')
            .onCreate(async (snapshot, context) => {
                const articleCategory = context.params.articleCategory;
                console.log('The article category is ' + articleCategory)

                const articleKey = context.params.articleKey;
                console.log('The article key is ' + articleKey)

                const userId = context.params.userId;
                console.log('The user id is ' + userId)

    // I can't seem to get the value of articleOwner
                const articleOwner;

                const articleOwnerRef = snapshot.ref.parent.parent;
                articleOwnerRef.once('value').then(parentSnap => {
                    const user = parentSnap.val();
                    articleOwner = user.article_owner;
                    console.log('The article owner is ' + articleOwner)
                });

                // get article owner promise
                const firstNamePromise = admin.database().ref(`/Users/${userId}/first_name`).once('value');
                const lastNamePromise = admin.database().ref(`/Users/${userId}/last_name`).once('value');
                const thumbImagePromise = admin.database().ref(`/Users/${userId}/thumb_image`).once('value');
                const notificationTokenPromise = admin.database().ref(`/Users/${articleOwner}/deviceToken`).once('value');


                // Snapshot to the user's firstName, lastName, thumbImage and notificationToken
                let firstName;
                let lastName;
                let notificationToken;
                let thumbImage;

                let tokens;

                const results = await Promise.all([firstNamePromise, lastNamePromise, thumbImagePromise, notificationTokenPromise]);
                firstName = results[0].val();
                console.log('The first name is ' + firstName)

                lastName = results[1].val();
                console.log('The last name is ' + lastName)

                thumbImage = results[2].val();
                console.log('The thumb image is ' + thumbImage)

                notificationToken = results[3].val();
                console.log('The device notification is ' + notificationToken)





                // check if there are any device tokens
                // if (!notificationToken.hasChildren()) {
                //     return console.log('There are no notification tokens to send to');
                // }

                console.log('The notification token is ' + notificationToken)

                // Notification details
                const payload = {
                    notification: {
                        title: 'Your story alert!',
                        body: `${firstName} ${lastName} liked your story`,
                        icon: thumbImage
                    }
                };

                // Listing all tokens as an array
                // tokens = Object.keys(notificationToken.val());

                // send notification to all tokens
                const response = await admin.messaging().sendToDevice(notificationToken, payload);

                // // For each message check if there was an error
                const tokensToRemove = [];
                // response.results.forEach((result, index) => {
                //     const error = result.error;
                //     if (error) {
                //         console.error('Failure sending notification to ', tokens[index], error);

                //         // Clean up the tokens who are not registered anymore
                //         if (error.code === 'messaging/invalid-registration-token'
                //             || error.code === 'messaging/registration-token-not-registered') {
                //             tokensToRemove.push(notificationToken.ref.child(tokens[index]).remove());
                //         }
                //     }
                // });
                 return Promise.all(tokensToRemove);
            });

0 个答案:

没有答案