从不同事件触发的 lambda 的 Typescript 语法
Typescript syntax for a lambda that is triggered from different events
我使用无服务器框架定义了一个可以每小时触发或通过 SNS 触发的 lambda
...
functions: {
fooAction: {
handler: 'handler.fooAction',
events: [
{
schedule: 'rate(1 hour)',
},
{
sns: {
topicName: 'fooTopic',
},
},
],
},
...
}
...
定义 fooAction
函数时正确的打字稿语法是什么?
我试过了
import { SNSHandler, ScheduledHandler} from 'aws-lambda';
...
export const fooAction: ScheduledHandler | SNSHandler = async (evt) => { ... };
但 evt
解析为 any
。
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;
}
};
我使用无服务器框架定义了一个可以每小时触发或通过 SNS 触发的 lambda
...
functions: {
fooAction: {
handler: 'handler.fooAction',
events: [
{
schedule: 'rate(1 hour)',
},
{
sns: {
topicName: 'fooTopic',
},
},
],
},
...
}
...
定义 fooAction
函数时正确的打字稿语法是什么?
我试过了
import { SNSHandler, ScheduledHandler} from 'aws-lambda';
...
export const fooAction: ScheduledHandler | SNSHandler = async (evt) => { ... };
但 evt
解析为 any
。
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;
}
};