網站搜尋

TypeScript 語法,用於由不同事件觸發的 lambda


使用 serverless 框架,我已定義了一個可以每小時觸發或通過 SNS 觸發的 Lambda 函數

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

定義 fooAction 函數時,正確的 TypeScript 語法是什麼?

我已經嘗試過

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

但是 evt 解析為 any。

答案#1

在 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;
    }
};