我正在尝试使用 typescript 的谷歌云功能。我希望该功能由来自 PubSub 的消息触发。函数的一般格式如下
exports.readMessage = async (event, context): Promise<void> => {
const message = event.data
? Buffer.from(event.data, "base64").toString()
: "No Message";
console.log(message);}
我有错误,因为 typescript 提示事件和上下文的任何类型。 package @google-cloud/PubSub 提到它导出了它的类型,但我没有看到任何与事件或上下文相关的类型。
关于我缺少什么以及我可以从哪个包导入类型的任何指示?
最佳答案
我没有使用这个库的经验,但我会尽力帮助你。
从代码来看,应该是接收来自Google Cloud Function (GCF)的消息,context实际上是GCF在Pub事件后返回的元数据。
事件应该是发布/订阅消息,所以类型是PubsubMessage
。
为了获取上下文类型,需要添加GCF库。
yarn add @google-cloud/functions-framework
or
npm install @google-cloud/functions-framework
// context type
import { Context } from "@google-cloud/functions-framework/build/src/functions";
// event message type
import { PubsubMessage } from "@google-cloud/pubsub/build/src/publisher";
exports.readMessage = async (event: PubsubMessage, context: Context): Promise<void> => {
// event.data can be Uint8Array|string|null, so need to cast it as string explicitly to allow base64 operations.
const message = event.data
? Buffer.from(event.data as string, "base64").toString()
: "No Message";
console.log(message);
}
关于谷歌云函数事件和上下文的 typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67458830/