Reputation: 3241
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
.
Upvotes: 9
Views: 13267
Reputation: 21144
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;
}
};
Upvotes: 18