npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

validation-failed-error-mapper

v2.0.0

Published

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

Downloads

9

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