Checking arguments of a Typescript AWS Lambda handler

So many times in the past few months I've been bitten by not supplying the AWS Lambda, written in Typescript, with proper input. So I have tested the Middy Validator Plugin. The plugin was so easy to use that I found myself startled I hadn't used the plugin before.

Here's how it works:

  1. You specify the input schema. For example for the json input:

    {"query": "some string here"}
    

    the schema would be

    const inputSchema = {
      required: ['query'],
      properties: {
        query: {
          type: 'string',
        },
      },
    }
    
  2. Once defined, you just need to attach the middleware to the lambda handler:

    export const queryExecutor = async (event: Event) => {/*...*/}
    const handler = middy(queryExecutor)
    handler.use(validator({inputSchema}))
    

The lambda will now fail if the input is invalid.

On top of early error detection, such validation also serves as an implicit documentation of the expected input.


-

If you need help with building the tech products get in touch.