如何订阅firebase函数,以便通过发布/订阅触发器执行

时间:2018-09-20 19:39:05

标签: firebase google-cloud-functions google-cloud-pubsub

已要求我创建一个触发onUpdate的firebase(fb)函数。然后,我必须从fb数据库中收集一堆信息并发布一条消息,以便在此点触发另一个函数。

fb更新触发功能A 函数A发布一条消息 functionB是该主题的订阅者,并且在消息发布后被触发。

我在下面具有onUpdate触发器的基础:

const functions = require("firebase-functions"),
  Promise = require("promise"),
  PubSub = require(`@google-cloud/pubsub`),
  admin = require("firebase-admin");

  const pubsub = new PubSub();

    exports.checkInOrder = functions.database
      .ref("/orders/{id}")
      .onUpdate((change, context) => {
        const after = change.after.val();
        // check the status: "pending-pickup" or "fulfilled" TODO
        if (after.status === "new") {
          console.log("ended because package is new.");
          return null;
        }

        let dsObj = {};
        const orderId = context.params.id;
        const topicName = 'check-in-order';
        const subscriptionName = 'check-in-order';

        return // how would I send the message to the pubsub here?
      });

所以总结一下:

  1. 如何向pubsub发送消息
  2. 如何在主题收到消息时订阅firebase函数来触发?

如果听起来很令人困惑,对不起-我在这里完全迷路了。谢谢!

1 个答案:

答案 0 :(得分:0)

所以我终于想通了。挺直截了当的,只是在匆忙的时间范围内一次学习所有这些东西而感到不知所措。下面是我的代码。我收录了整个页面,以防万一将来对别人有所帮助。

const functions = require("firebase-functions"),
  Promise = require("promise"),
  PubSub = require(`@google-cloud/pubsub`),
  admin = require("firebase-admin");

const init = () => {
    const topicName = "check-in-order";
  pubsub
    .createTopic(topicName)
    .then(results => {
      const topic = results[0];
            console.log(`Topic ${topicName} created.`);
            return;
    })
    .catch(err => {
            console.error("ERROR on init:", err);
            return;
    });
};

const pubsub = new PubSub();

exports.orderCreated = functions.database
  .ref("/orders/{id}")
  .onUpdate((change, context) => {
        console.log("it's happening!");
        const after = change.after.val();
        console.log("after::::>", after)

    if (after.status === "new") {
            console.log('stopped because status is new');
      return null;
    }

    if (after.status === "pending-pickup" || after.status === "fulfilled") {
            const orderId = context.params.id;
            const topicName = "check-in-order";
            let { assignedSlot, userId, parcelLockerId, carrier, trackingNumber, orderInDate, pickUpCode, status,  } = after;
            const dsObj = {
                order: {
                        orderId,
                        userId,
                        parcelLockerId,
                        carrier,
                        trackingNumber,
                        orderInDate,
                        pickUpCode,
                        status,
                }
         };      

            const dataBuffer = new Buffer.from(dsObj.toString());

            // publish to trigger check in function
            return pubsub
                .topic(topicName)
                .publisher()
                .publish(dataBuffer)
                .then(messageId => {
                    console.log(`:::::::: Message ${messageId} has now published. :::::::::::`);
                    return true;
                })
                .catch(err => {
                    console.error("ERROR:", err);
                    throw err;
                });
        }
        return false;
    });

exports.checkInOrder = () => {

}
exports.checkIn = functions.pubsub.topic('check-in-order').onPublish((message) => {
    console.log("everything is running now", message);
    return true;
});

init();