【问题标题】:Typescript types for google cloud function's event and context谷歌云函数事件和上下文的打字稿类型
【发布时间】:2021-05-09 14:28:37
【问题描述】:

我正在使用打字稿尝试谷歌云功能。我希望该功能由来自 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 提到它导出了它的类型,但我没有看到任何与事件或上下文相关的类型。

任何指向我缺少什么以及我可以从哪个包导入类型的指针?

【问题讨论】:

  • 我的回答能帮到你吗?如果没有,您能否提供更多详细信息?

标签: typescript function cloud publish-subscribe


【解决方案1】:

我没有使用此库的经验,但会尽力帮助您。

从代码来看,它应该是接收来自 Google Cloud Function (GCF) 的消息,而上下文实际上是 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);
}

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2021-12-24
    • 2012-11-18
    • 2020-07-28
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2017-06-24
    相关资源
    最近更新 更多