0

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.

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:

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.

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

1 Answer 1

1

You can create a function to wrap lambda handler function to your function.

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.

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.

Update: Generic version, customHander accepts any type as 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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @hoangdv, this is helpful but I was wondering if there's a way to have a generic customHandler that can handle any of my functions. Say I have these two methods: getListOfObjects(MyRequestFilter): createOneObject(MyCreateRequestObject): Where i'd want const body = JSON.parse(event.body) as MyRequestObject; to instead of being one object, to be either MyCreateRequestObject or MyRequestFilter depending on what function is passed to the customHandler
Thank you. Appreciate the help.

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.