简体   繁体   English

AWS Lambda 自定义参数

[英]AWS Lambda Custom Parameters

I am getting started with a serverless application and you define functions as this:我开始使用无服务器应用程序,您将函数定义为:

exports.handler = async function(event, context) { from what I've seen and I have not been able to find any examples where the parameters are different. exports.handler = async function(event, context) {从我所看到的,我无法找到任何参数不同的例子。

I was wondering if there was any point in the flow where I could use event to parse as MyRequestObject and then define my method as:我想知道流程中是否有任何一点可以使用事件解析为 MyRequestObject 然后将我的方法定义为:

exports.handler = async function(MyRequestObject) {

I'm trying to use openAPI and go with a contract based API that is clearly defined and create SDKs from the code so I'm looking to make it pretty specific if possible.我正在尝试使用 openAPI 并使用明确定义的基于合同的 API 并从代码创建 SDK,因此我希望尽可能使其非常具体。

I know that I can do inside the function the following:我知道我可以在函数内部执行以下操作:

const MyObject: MyObject = JSON.parse(event.body) as MyObject;

but I'm looking to have one method that maybe uses reflection to then pass the correct object depending on what the function is expecting.但我希望有一种方法可以使用反射然后根据函数的期望传递正确的对象。

Thank you谢谢

You can create a function to wrap lambda handler function to your function.您可以创建一个函数来将 lambda 处理程序函数包装到您的函数中。

interface MyRequestObject {
  name: string;
}

const customHandler = (func: (params: MyRequestObject) => Promise<any>) => {
  return async (event, context) => {
    const body = JSON.parse(event.body) as MyRequestObject;
    return await func(body);
  }
}

exports.handler = customHandler(async (params: MyRequestObject) => {
  // do something with param
  // return the result
});

customHandler will return a function, this is lambda handler function. customHandler将返回一个函数,这是 lambda 处理函数。

Inside of the function, it tries to convert event.body to MyRequestObject and executes func (your function), then returns result of func as result of lambda function.里面的功能,它会尝试把event.bodyMyRequestObject和执行func (你的函数),然后返回结果的func作为lambda表达式的结果。

Update : Generic version, customHander accepts any type as params更新:通用版本, customHander接受任何类型作为params

const customHandler = <T extends {}>(func: (params: T) => Promise<any>) => {
  return async (event, context) => {
    const body = JSON.parse(event.body) as T;
    return await func(body);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM