简体   繁体   中英

How to make a function that can be called in other functions in Cloud Functions?

I have the following case, when deleting any data, I need to delete the app badges (at the moment I delete them using silent push notication and reduce the app badges number with the cloud function) if the user who sent the request has deleted. But since the user who deleted could send several requests to different users in different places, so I decided that I need to create a function that will be called in firebase database trigger functions and also it will help not to duplicate the same code everywhere .

The function will be approximate such

function adminRemoveAppBadge(userID, dataID, categoryID) {

};

And for example, call it in this function

module.exports = functions.database.ref('/cards/{cardID}/interestedUsers/{interestedUserID}').onWrite(event => {

    const currentData = event.data.current;
    const prevData = event.data.previous;

    const cardID = event.params.cardID;
    const interestedUserID = event.params.interestedUserID;

    if (currentData.val() && !prevData.val()) {
        // value created
        return console.log('cardInterestedUserHandler - created');
    } else if (!currentData.val() && prevData.val()) {
        // value removed
        console.log('cardInterestedUserHandler - removed', currentData.val());

        const cardRef = admin.database().ref("cards").child(cardID);
        const cardRefPromise = cardRef.once("value", function(snap, error) {
            if (error) {
              return error;
            };
            if (snap.val()) {
                const cardJSON = snap.val();
                const cardOwnerID = cardJSON["ownerID"];

                if (cardOwnerID) {
                    const cardOwnerAppBadgesRef = admin.database().ref("userAppBadges").child(cardOwnerID).child("appBadgeModels").orderByChild("dataID").equalTo(cardID);
                    const cardOwnerAppBadgesRefPromise = cardOwnerAppBadgesRef.once("value", function (cardOwnerAppBadgesRefSnap, error) {
                        if (error) {
                            return error;
                        };
                        if (cardOwnerAppBadgesRefSnap.val()) {
                            var deletingPromises = [];
                            cardOwnerAppBadgesRefSnap.forEach(function(cardOwnerAppBadgesRefSnapChild) {
                                const appBadgeModelJSON = cardOwnerAppBadgesRefSnapChild.val();
                                const appBadgeModelID = appBadgeModelJSON["id"];
                                const senderID = appBadgeModelJSON["senderID"];
                                if (appBadgeModelID && senderID) {
                                    if (senderID == interestedUserID) {
                                        const cardOwnerAppBadgeRef = admin.database().ref("userAppBadges").child(cardOwnerID).child("appBadgeModels").child(cardOwnerAppBadgeModelID);
                                        const cardOwnerAppBadgeRefPromise = cardOwnerAppBadgeRef.remove();
                                        deletingPromises.push(cardOwnerAppBadgeRefPromise);


                                        // to call 
                                        adminRemoveAppBadge
                                    };
                                } else {
                                    console.log("cardOwnerAppBadgeModelID == null");
                                };
                            });

                            return Promise.all(deletingPromises);
                        };
                    });
                    return Promise.all([cardOwnerAppBadgesRefPromise]);
                } else {
                  return console.log("owner id == null");
                };
            };
        });
        return Promise.all([cardRefPromise]);
    } else {
        return console.log('cardInterestedUserHandler - updated');
    };
});

Also functions are in different files. How can I call it in other firebase cloud functions and how do I deploy this function?

Update I tried to do so one of the options as written here and here , but when I tried to do deploy I got an error Cannot find module 'AppBadges/adminRemoveAppBadge.js' .

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

exports.adminRemoveAppBadge = function (userID, dataID, categoryID) {

    console.log("adminRemoveAppBadge nil");
};

Requested this function so

var adminRemoveAppBadgeModule = require("AppBadges/adminRemoveAppBadge.js");

and call this functions so

adminRemoveAppBadgeModule.adminRemoveAppBadge(cardOwnerID, cardID, 0);

Google Functions are just JS - so normal routes to include code work.

I place my "library" functions in a folder /lib So my functions folder looks like this:

/functions
   /lib
       BuildImage.js
       SendEmail.js
index.js
package.json
...etc...

within my index.js I just include my code:

const SendMail = require('./lib/SendMail')
const sendMail = new SendMail({
  database: db,
  mailgun: mailgun
})
exports.sendContactUsMessage = functions.database.ref('/contact-messages/{itemId}').onWrite(sendMail.send(event))

EDIT Added /lib/SendMail.js code:

module.exports = class SendMail {
constructor(config) {
  if (!config) {
    throw new Error ('config is empty. Must pass database and mailgun settings')
  }
  if (!config.database) {
    throw new Error('config.database is empty. Must pass config.database')
  }
  if (!config.mailgun) {
    throw 'config.mailgun is empty. Must pass config.mailgun'
  }
  this.database = config.database
  this.mailgun = config.mailgun
}

sendEmail (emailData) {
  return new Promise((resolve, reject) => {
    this.mailgun.messages().send(emailData, (error, body) => {
      if (error) {
        if (debug) {
          console.log(error)
        }
        reject(error)
      } else {
        if (debug) {
          console.log(body)
        }
        resolve(body)
      }
    })
  })
}
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM