如何创建一个可以在云函数中的其他函数中调用的函数?

时间:2017-08-07 08:01:35

标签: javascript firebase google-cloud-functions

我有以下情况,当删除任何数据时,我需要删除应用徽章(目前我使用静态推送通知删除它们并使用云功能减少应用徽章编号)如果发送请求的用户已删除。但是由于删除的用户可以向不同地方的不同用户发送多个请求,因此我决定创建一个将在firebase数据库触发器函数中调用的函数,并且它还有助于不在任何地方复制相同的代码。 / p>

该功能将近似为

function adminRemoveAppBadge(userID, dataID, categoryID) {

};

例如,在此函数中调用它

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');
    };
});

功能也在不同的文件中。如何在其他firebase云功能中调用它以及如何部署此功能?

更新我尝试按照herehere编写的选项之一,但当我尝试部署时出现错误无法找到模块'AppBadges / adminRemoveAppBadge.js'

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

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

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

请求此功能

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

并调用此函数

adminRemoveAppBadgeModule.adminRemoveAppBadge(cardOwnerID, cardID, 0);

1 个答案:

答案 0 :(得分:2)

Google功能只是JS - 所以包含代码工作的常规路由。

我将“库”功能放在/lib文件夹中 所以我的函数文件夹如下所示:

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

在我的index.js中我只包含我的代码:

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))

编辑添加了/lib/SendMail.js代码:

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)
      }
    })
  })
}
...
}