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](https://middy.js.org/packages/validator/).
The plugin was so easy to use that I found myself startled I hadn't used the plugin before. (By the way, I'm a big fan of Middy, since it [decomplects code into simpler reusable components](middleware%20might%20help%20simplify%20handlers.md)
Here's how it works:
1. You specify the input schema. For example for the json input:
```json
{ "query": "some string here" }
```
the schema would be
```typescript
const inputSchema = {
required: ["query"],
properties: {
query: {
type: "string",
},
},
}
```
2. Once defined, you just need to attach the middleware to the lambda handler:
```typescript
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.
Related:
- [[external data might be unexpected, early data validation could help]]