10

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.

0

1 Answer 1

18

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;
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I believe EventBridgeEvent<"Scheduled Event", any> should be EventBridgeEvent<"Scheduled Event", string>. EventBridge seems to JSON.stringify the details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.