koa-jsonschema

0.1.0 • Public • Published

Koa JSONSchema

Build Status NPM version Dependency Status devDependency Status

A Koa middleware for validate JSONSchema

Installation

$ npm install --save koa-bodyparser@3 koa-jsonschema

Usage

const bodyParser = require('koa-bodyparser');
const schema = require('..');
const koa = require('koa');
 
const app = new koa();
app.use(bodyParser());
app.use((ctx, next) => {
  next().catch(e => {
    if (e.message === 'JSONSchema errors') {
      // If validation errors, errors will store in `ctx.schemaErrors`.
      ctx.body = ctx.schemaErrors;
    }
  });
});
app.use(schema({
  type: 'object',
  properties: {
    a: { type: 'string' },
    b: { type: 'string' }
  },
  required: ['a', 'b']
}));
app.use(function(ctx, next) {
  ctx.body = ctx.request.body;
});
 
app.listen(3000);

If you're still using koa@1, use .legacy for koa 1.0 middleware.

const schema = require('koa-jsonschema').legacy;

schema function arguments

schema Object

Refer to JSONSchema documentation for made schema.

validator The JSONSchema validator

Can be null, it means you can customize it. (see this example)
It will validate ctx.request.body, so you should use koa-bodyparser middleware.
If validation errors, errors will store in ctx.schemaErrors.

pass Boolean

Ignore the error and pass middleware.

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i koa-jsonschema

Weekly Downloads

9

Version

0.1.0

License

MIT

Last publish

Collaborators

  • jhen0409