Search code examples
typescriptaws-lambdaamazon-snsserverless-frameworkaws-event-bridge

Typescript syntax for a lambda that is triggered from different events


Using the serverless framework I have defined a lambda that can be either triggered every hour or via SNS

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

What is the correct typescript syntax when defining fooAction function?

I have tried

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

but evt resolves to any.


Solution

  • There seems to be a type Handler in aws-lambda sdk, which is generic and can be used for situations like this,

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

    You can also define your own type based on these two different function types.

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

    And then, use this new type with your lambda function,

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