ant*_*iom 9 amazon-sns typescript aws-lambda serverless-framework aws-event-bridge
使用无服务器框架,我定义了一个 lambda,可以每小时触发一次或通过 SNS 触发
...
functions: {
fooAction: {
handler: 'handler.fooAction',
events: [
{
schedule: 'rate(1 hour)',
},
{
sns: {
topicName: 'fooTopic',
},
},
],
},
...
}
...
Run Code Online (Sandbox Code Playgroud)
定义函数时正确的打字稿语法是什么fooAction?
我努力了
import { SNSHandler, ScheduledHandler} from 'aws-lambda';
...
export const fooAction: ScheduledHandler | SNSHandler = async (evt) => { ... };
Run Code Online (Sandbox Code Playgroud)
但evt决心any。
San*_*eep 18
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;
}
};
Run Code Online (Sandbox Code Playgroud)
您还可以根据这两种不同的函数类型定义自己的类型。
type CustomEvent = (event: SNSEvent | EventBridgeEvent<"Scheduled Event", any>, context: Context, callback: Callback<void>) => Promise<void> | void
Run Code Online (Sandbox Code Playgroud)
然后,将这个新类型与您的 lambda 函数一起使用,
const fooHandler: CustomEvent = (event) => {
if ('Records' in event ) {
// SNSEvent
const records = event.Records;
// so something
} else {
const { id, version, region, source } = event;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10550 次 |
| 最近记录: |