如何向我的 Pub/Sub Cloud Run (gen2) 函数添加类型安全?

问题描述 投票:0回答:1

我有一个运行 TypeScript/Node.js 的 Google Cloud Run Function(以前称为 Cloud Functions 2nd Gen)。 Pub/Sub 教程中的文档显示您获得了

cloudEvent
,但是如何为其添加类型安全性?

特别是如果我想定义属性或消息正文的类型。

这是他们的例子:

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent callback with the Functions Framework that will
// be executed when the Pub/Sub trigger topic receives a message.
functions.cloudEvent('helloPubSub', cloudEvent => {
  // The Pub/Sub message is passed as the CloudEvent's data payload.
  const base64name = cloudEvent.data.message.data;

  const name = base64name
    ? Buffer.from(base64name, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);
});
node.js typescript google-cloud-functions google-cloud-pubsub
1个回答
0
投票

@google-cloud/functions-framework
中定义了一些类型。

npm install @google-cloud/functions-framework@^3.3.0

然后你可以使用以下代码定义自己的类型:

import functions, { CloudEvent } from '@google-cloud/functions-framework'
import { RawPubSubBody } from '@google-cloud/functions-framework/build/src/pubsub_middleware'

/**
 * We get them as `attributes?: { [key: string]: string }`
 * But since we know the structure, we can define it as an interface
 */
interface PubSubAttributes {
  myTestAttribute: string
}

/** Extend the RawPubSubBody to use PubSubAttributes */
interface FunctionPubSubBody extends RawPubSubBody {
  message: {
    attributes: PubSubAttributes
  } & RawPubSubBody['message']
}

/** An interface that defines the shape of the body of the message */
interface PubSubBodyData {
  testBodyParam: string
}

// https://cloudevents.github.io/sdk-javascript/classes/CloudEvent.html
functions.cloudEvent<FunctionPubSubBody>(
  'syncAllMoviesNode',
  // You don't technically need to declare this type (it's inferred from above)
  async (cloudEvent: CloudEvent<FunctionPubSubBody>) => {
    console.log(cloudEvent)

    // The Pub/Sub message is passed as the CloudEvent's data payload.
    // It's base64 encoded, so we need to decode it and parse it as JSON.
    const base64Data = cloudEvent.data.message.data
    const base64String = Buffer.from(base64Data, 'base64').toString()
    const pubSubBody: PubSubBodyData = JSON.parse(base64String)

    const pubSubAttributes: PubSubAttributes = cloudEvent.data.message.attributes

    // The "Message Body" with type PubSubBodyData
    console.log(pubSubBody)

    // The "Attributes" as PubSubAttributes
    console.log(pubSubAttributes)
  }
)

在云调度程序中配置

cloud-scheduler-config

属性 vs 身体

这个 Reddit 帖子有一些想法,但我的要点是:

  • 使用将应用于跨调用的结构化元数据的属性
  • 将主体用于可能会根据调用/事件而变化的事物(您可能支持几种不同的“类型”,例如关闭属性)
    • 一个属性
      bodyType
      ,它是
      SYNC | CLEAR
    • 的枚举
    • 两种不同的消息正文“类型”
      SyncMessageBody
      ClearMessageBody

但说实话,你可以随心所欲地使用它们。

© www.soinside.com 2019 - 2024. All rights reserved.