google 云函数的事件和上下文的打字稿类型
Typescript types for google cloud function's event and context
我正在尝试使用打字稿 google 云函数。我希望该功能由来自 PubSub 的消息触发。函数的一般格式如下
exports.readMessage = async (event, context): Promise<void> => {
const message = event.data
? Buffer.from(event.data, "base64").toString()
: "No Message";
console.log(message);}
我有错误,因为打字稿抱怨事件和上下文的任何类型。包@google-cloud/PubSub 提到它导出了它的类型,但我没有看到任何与事件或上下文相关的类型。
关于我缺少什么以及我可以从哪个包导入类型的任何指示?
我没有使用这个库的经验,但我会尽力帮助你。
从代码来看,应该是接收来自Google Cloud Function (GCF)的消息,context实际上是GCF在Pub事件后返回的元数据。
事件应该是pub/sub消息,所以类型是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);
}
我正在尝试使用打字稿 google 云函数。我希望该功能由来自 PubSub 的消息触发。函数的一般格式如下
exports.readMessage = async (event, context): Promise<void> => {
const message = event.data
? Buffer.from(event.data, "base64").toString()
: "No Message";
console.log(message);}
我有错误,因为打字稿抱怨事件和上下文的任何类型。包@google-cloud/PubSub 提到它导出了它的类型,但我没有看到任何与事件或上下文相关的类型。
关于我缺少什么以及我可以从哪个包导入类型的任何指示?
我没有使用这个库的经验,但我会尽力帮助你。
从代码来看,应该是接收来自Google Cloud Function (GCF)的消息,context实际上是GCF在Pub事件后返回的元数据。
事件应该是pub/sub消息,所以类型是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);
}