2

I'm writing a validation schema for a serverless endpoint using ajv and this @middy/validator middleware. There is a note in documentation that the middleware can use external plugins. But it's not clear how to apply them, and there is no example. I want to use ajv-errors plugin for custom error messages, https://github.com/ajv-validator/ajv-errors.

Please drop me a link about how to apply an external plugin or give me an example. Thanks in advance!

Ivan Banha
  • 753
  • 2
  • 12
  • 23

1 Answers1

1

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:

  1. 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()
]);
  1. 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.

Markussen
  • 164
  • 1
  • 13