首页 > 解决方案 > Firebase Emulator Suite - 简单的 pubsub 示例

问题描述

我已经阅读了许多关于使用 Firebase Emulator Suite 尝试简单的 pubsub 设置的文档/博客/SO 文章,但似乎无法让 Emulator 接收消息。

我有 2 个功能functions/index.js

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

const PROJECT_ID = 'my-example-pubsub-project';
const TOPIC_NAME = 'MY_TEST_TOPIC';

// receive messages to topic
export default functions.pubsub
  .topic(TOPIC_NAME)
  .onPublish((message, context) => {
    console.log(`got new message!!! ${JSON.stringify(message, null, 2)}`);
    return true;
  });

// publish message to topic
export default functions.https.onRequest(async (req, res) => {
  const { v1 } = require('@google-cloud/pubsub');
  const publisherClient = new v1.PublisherClient({
    projectId: process.env.GCLOUD_PROJECT,
  });
  const formattedTopic = publisherClient.projectTopicPath(PROJECT_ID, TOPIC_NAME);

  const data = JSON.stringify({ hello: 'world!' });

  // Publishes the message as JSON object
  const dataBuffer = Buffer.from(data);
  const messagesElement = {
    data: dataBuffer,
  };
  const messages = [messagesElement];

  // Build the request
  const request = {
    topic: formattedTopic,
    messages: messages,
  };

  return publisherClient
    .publish(request)
    .then(([responses]) => {
      console.log(`published(${responses.messageIds}) `);
      res.send(200);
    })
    .catch((ex) => {
      console.error(`ERROR: ${ex.message}`);
      res.send(555);
      throw ex; // be sure to fail the function
    });
});

当我运行firebase emulators:start --only functions,firestore,pubsub然后运行 ​​HTTP 方法时wget -Sv -Ooutput.txt --method=GET http://localhost:5001/my-example-pubsub-project/us-central1/httpTestPublish,HTTP 函数运行并且我看到它的控制台输出,但我似乎无法.onPublish()运行。

我注意到,如果我弄乱了 的值v1.PublisherClient({projectId: PROJECT_ID}),那么我会在订阅的 GCP 云实例中显示一条消息……但这正是我希望发生的事情:)

标签: google-cloud-functionsgoogle-cloud-pubsubfirebase-tools

解决方案


推荐阅读