【问题标题】:How to subscribe a firebase function so that it executes via a pub/sub trigger如何订阅 firebase 函数,以便它通过 pub/sub 触发器执行
【发布时间】:2019-02-25 04:19:53
【问题描述】:

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

fb 更新触发 functionA functionA 发布消息 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 函数以在主题收到消息时触发?

如果这听起来很令人困惑,我很抱歉 - 我完全迷路了。谢谢!

【问题讨论】:

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


【解决方案1】:

所以我终于想通了。非常直截了当,只是在匆忙的时间内一次学习所有这些东西让我感到不知所措。下面是我的代码。我包含了整个页面,以防将来可能对其他人有所帮助。

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

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2019-04-17
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2021-02-21
    • 2020-09-26
    • 2023-02-12
    • 1970-01-01
    相关资源
    最近更新 更多