我有一个运行 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}!`);
});
@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)
}
)
这个 Reddit 帖子有一些想法,但我的要点是:
bodyType
,它是 SYNC | CLEAR
SyncMessageBody
和 ClearMessageBody
但说实话,你可以随心所欲地使用它们。