validation-failed-error-mapper

Validation failed error mapper for koa-error-mapper based on validator.js violations

Usage no npm install needed!

<script type="module">
  import validationFailedErrorMapper from 'https://cdn.skypack.dev/validation-failed-error-mapper';
</script>

README

validation-failed-error-mapper

Validation failed error mapper for koa-error-mapper based on validator.js violations.

Status

npm version node version build status

Installation

Install the package via yarn:

$ yarn add validation-failed-error-mapper

or via npm:

$ npm install validation-failed-error-mapper --save

Usage

Create a validation failed error

To use this mapper you need to define which error class it will map. Each instance of your validation failed error should have all violations on the errors property.

For example:

import StandardError from 'standard-error';

export default class ValidationFailedError extends StandardError {
  constructor(errors) {
    super({ errors });
  }
}

Instantiate the mapper

Instantiate a new mapper with your validation failed error class and add it to the error mapper middleware:

import Koa from 'koa';
import ValidationFailedError from './my-validation-failed-error';
import ValidationFailedErrorMapper from 'validation-failed-error-mapper';
import errorMapper from 'koa-error-mapper';

export const app = new Koa();

app.use(errorMapper([new ValidationFailedErrorMapper(ValidationFailedError)]));
app.listen();

Mapping format

Assume the following example where your application validates the request body against some constraint:

import { Assert as is, Validator } from 'validator.js';
import { app } from './my-app';
import ValidationFailedError from './my-validation-failed-error';

app.use(async (ctx, next) => {
  const errors = new Validator().validate(ctx.request.body, {
    foo: is.notBlank(),
    bar: is.ofLength({ min: 1, max: 2 })
  });

  if (errors !== true) {
    throw new ValidationFailedError(errors);
  }

  await next();
});

The following request:

curl http://localhost:3000 \
  -H 'Content-Type: application/json' \
  -d '{ "foo": "", "bar": "biz" }'

Will respond with 400 status and the following body:

{
  "message": "Validation failed",
  "code": "validation_failed",
  "errors": {
    "foo": [{
      "code": "not_blank",
      "message": "This value must not be blank"
    }],
    "bar": [{
      "args": {
        "min": 1,
        "max": 2
      },
      "code": "length",
      "message": "This value must have between 1 and 2 characters"
    }]
  }
}

Messages

All asserts from validator.js and validator.js-asserts have pre-defined messages, although you can override them and add your own custom messages as the mapper second constructor argument.

The message property can be defined as a function that receives the violation or a template string to generate more dynamic output.

The args property can also be defined as a function that receives the violation or a list of strings that should match the assert's properties.

import ValidationFailedError from './my-validation-failed-error';
import ValidationFailedErrorMapper from 'validation-failed-error-mapper';
import Validator from 'validator.js';

export default new ValidationFailedErrorMapper(ValidationFailedError, {
  EqualTo: {
    message: 'This value must be equal to other value'
  }
  CustomEqualTo: {
    args: ['reference'],
    message: 'This value is supposed to be equal {reference}'
  },
  EqualToOr: {
    args({ assert: { reference1, reference2 } }) {
      return {
        reference1,
        reference2
      }
    },
    message({ assert: { reference1, reference2 } }) {
      return `This value must be equal to ${reference1} or ${reference2}`;
    }
  },
  NotBlank() {
    message({ violation }) {
      if (violation && violation.value === Validator.errorCode.must_be_a_string) {
        return 'This value must be a string';
      }

      return 'This value must not be blank';
    }
  }
});

Note that the message key must match the assert __class__ value. If an assert does not have a message the following default message will be mapped:

{
  "foo": [{
    "code": "invalid",
    "message": "This value in invalid"
  }]
}

Test suite

Use the test script to run the test suite:

$ yarn test

To test check coverage use the cover script:

$ yarn cover

A full coverage report will be generated on coverage folder.

Release

$ yarn release [<version> | major | minor | patch]

License

MIT