JSON schema validator middleware for Egg.js.
$ npm i egg-validate-middleware --save
// {app_root}/config/plugin.js
exports.validateMiddleware = {
enable: true,
package: 'egg-validate-middleware',
};
// {app_root}/config/config.default.js
exports.validateMiddleware = {
formatResponse: null
};
formatResponse
is used to pack response's schema define to make sure all response data has same format. Only effective when schema had response
define.
// response schema
const schema = {
response: {
type: 'string'
}
}
// will allow response like { code: 200, message: 'message', data: 'response' }
formatResponse(responseSchema) {
return {
type: 'object',
properties: {
code: { type: 'number' },
message: { type: 'string' },
data: responseSchema,
},
};
}
see config/config.default.js for more detail.
All schemas must defined at app/schema
, and will auto load to app.schema
.
// app/schema/home.js
module.exports = {
index: {
// [option] Used to validte input params
request: {
query: {
type: 'object',
properties: {
// query string params
}
},
params: {
type: 'object',
properties: {
// url params
}
},
body: {
// request body
}
},
// [option] Used to format and fast stringify response data
response: {
type: 'object',
properties: {
// response format
}
}
}
};
Schema and controller should be one-to-one correspondence.
// app/schema/home.js
module.exports = {
index: {
// ...
}
};
// should match to
// app/controller/home.js
class HomeController extends Controller {
async index() {
// return data, no need to set ctx.body
return 'something';
}
}
This middleware should be placed in front of the controller:
// app/router.js
module.exports = app => {
const { router, controller, middleware, schema } = app;
const { validate } = middleware;
router.get('/home/index', validate({ schema: schema.home.index }), controller.home.index);
}
see test for more detail.
Please open an issue here.