I´m not familiar with ajv but I´ve used middy/validator.
Assuming you have a lambda function that expectes a JSON body and has the next simple code (just returns the JSON body received):
async function test(event, context) {
return {
statusCode: 200,
body: JSON.stringify(event.body),
};
}
export const handler = test;
My suggestion (and what worked for me) is the following:
- Create a middleware file (ie: middleware.js) with the components your middleware needs. If you need to use middy/validator, you need to also add middy/http-json-body-parser so it parses the JSON body into an object the validator can inspect. This file can look like:
import middy from '@middy/core';
import httpEventNormalizer from '@middy/http-event-normalizer';
import jsonBodyParser from '@middy/http-json-body-parser';
import httpErrorHandler from '@middy/http-error-handler';
export default handler => middy(handler)
.use([
httpEventNormalizer(),
jsonBodyParser(),
httpErrorHandler()
]);
- Now import this file in the lambda function where you want to use the validator and "wrap" your handler with it. The lambda function should now look like:
import middleware from '../lib/middleware'
import validator from '@middy/validator';
import yourSchema from '../lib/yourSchema';
async function test(event, context) {
return {
statusCode: 200,
body: JSON.stringify(event.body),
};
}
export const handler = middleware(test)
.use(validator({inputSchema: yourSchema}));
Where "yourSchema" is the validation schema you built.