google-cloud-functions - 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 云实例中显示一条消息……但这正是我不希望发生的事情:)
解决方案
推荐阅读
- android - JetpackCompose 中 @Preview 的 isInEditMode 模拟
- android - 我如何将列表视图项目居中
- r - 通过 shell 执行包含 read_sf 的 R 脚本时无法打开“--file=script.r”
- zabbix - 如何打开10051端口
- mysql - Sequelize(1个用户有很多帖子,1个帖子有1个用户,1个帖子有很多评价属于一个用户)
- python - Pycharm 警告 - '相对导入包外'
- ios - 如何初始化 UIDocumentPickerViewController 注意到“forOpeningContentTypes”(来自 doco)在 IOS 中似乎已被弃用?
- r - 带有 MPICH Virgin Build DoMPI 的 Ubuntu 21.04 桌面上的 Rmpi
- python - 使用 Python MoviePY 渲染视频太慢
- javascript - Semantic UI React `Dropdown` - 通过鼠标和键盘进行单选行导航