8

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.

antoniom
  • 3,143
  • 1
  • 37
  • 53

1 Answers1

16

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;
    }
};
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • 4
    Just stumbled across this comment while looking into the same use-case. Consider creating a lambda function per event source to avoid the if/else logic within your Lambda function. – Seth Geoghegan Oct 18 '22 at 22:00
  • I believe `EventBridgeEvent<"Scheduled Event", any>` should be `EventBridgeEvent<"Scheduled Event", string>`. EventBridge seems to JSON.stringify the details. – gamliela Apr 12 '23 at 23:25