koa2-json-schema
v1.0.0
Published
Middleware for validate request body by JSON schemas.
Downloads
14
Maintainers
Readme
Koa2 JSON Schema
Middleware for validate request body by JSON schemas.
Install
$ npm i koa2-json-schema
Tests
$ npm test
Basic usage
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const jsonSchema = require('koa2-json-schema')()
const app = new Koa()
const router = new Router()
router.post('/users', jsonSchema({
first_name: 'string',
last_name: 'string',
phone: 'number'
}), (ctx) => {
// API...
})
app.use(bodyParser())
app.use(router.routes())
app.listen(3000)
Advanced usage
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const jsonSchema = require('koa2-json-schema')()
const app = new Koa()
const router = new Router()
router.post('/users', jsonSchema({
preferences: {
type: 'array',
items: {
type: 'object',
required: [
'title',
'description'
],
properties: {
title: 'string',
description: 'string'
}
}
}
}), (ctx) => {
// API...
})
app.use(bodyParser())
app.use(router.routes())
app.listen(3000)
Error handling
By default, by sending the incorrect data in body, the server will return an error. This is the default error handler in koa2-json-schema.
ctx.status = 400
ctx.body = { error: errors }
But if you want to transfer control to the next middleware you must set the flag.
router.post('/users', jsonSchema({
preferences: {
type: 'array',
items: {
type: 'object',
required: [
'title',
'description'
],
properties: {
title: 'string',
description: 'string'
}
}
}
}, true), (ctx) => { // flag is true
// now you can handle errors from ctx.errors
// these are errors if the body is empty
// ctx.errors = [ 'preferences must be array' ]
})
Strict mode
You can enable strict mode which throw errors when client sent extra field in body. So, if you want enable strict mode, set true
in third argument in jsonSchema
function.
router.post('/users', jsonSchema({
preferences: 'array'
}, true, true), (ctx) => {
// ^ transfer errors is true, ^ strict mode is true (enable)
// now you can handle errors from ctx.errors
// these are errors if the body is valid preferences and unsued field age
// ctx.errors = [ 'age field(s) are unused, you mustn\'t send them' ]
})
Locales
You can easily switch locales or create custom.
Native locales:
// import russian locales
const ru = require('koa2-json-schema/locales/ru')
// passed new locales into argument when require
const jsonSchema = require('koa2-json-schema')(ru)
Custom locales:
// %property% and %type% are dynamic variables
const jsonSchema = require('koa2-json-schema')({
propertyIsRequired: '%property% is really required, bro 😞',
invalidValueType: '%property% must be %type% type 😊'
})
License
MIT.