4

使用无服务器框架,我定义了一个可以每小时触发或通过 SNS 触发的 lambda

  ...
  functions: {
    fooAction: {
      handler: 'handler.fooAction',
      events: [
        {
          schedule: 'rate(1 hour)',
        },
        {
          sns: {
            topicName: 'fooTopic',
          },
        },
      ],
    },
   ...
  }
  ...

定义fooAction函数时正确的打字稿语法是什么?

我试过了

import { SNSHandler, ScheduledHandler} from 'aws-lambda';
...
export const fooAction: ScheduledHandler | SNSHandler = async (evt) => { ... };

evt解决为any.

4

1 回答 1

10

在 aws-lambda sdk 中似乎有一个类型Handler,它是通用的,可以用于这样的情况,

import { SNSEvent, EventBridgeEvent, Handler } from 'aws-lambda';

const fooHandler: Handler<SNSEvent | EventBridgeEvent<any, any>> = (event) => {
    if ('Records' in event ) {
        // SNSEvent
        const records = event.Records;
        // so something
    } else {
        const { id, version, region, source } = event;
    }
};

您还可以根据这两种不同的函数类型定义自己的类型。

type CustomEvent = (event: SNSEvent | EventBridgeEvent<"Scheduled Event", any>, context: Context, callback: Callback<void>) => Promise<void> | void

然后,将这种新类型与您的 lambda 函数一起使用,

const fooHandler: CustomEvent = (event) => {
    if ('Records' in event ) {
        // SNSEvent
        const records = event.Records;
        // so something
    } else {
        const { id, version, region, source } = event;
    }
};
于 2021-02-28T21:58:40.317 回答