egg-validate-middleware
JSON schema validator middleware for Egg.js.
Install
$ npm i egg-validate-middleware --save
Usage
// {app_root}/config/plugin.jsexportsvalidateMiddleware = enable: true package: 'egg-validate-middleware';
Configuration
// {app_root}/config/config.default.jsexportsvalidateMiddleware = 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 schemaconst schema = response: type: 'string' // will allow response like { code: 200, message: 'message', data: 'response' } { return type: 'object' properties: code: type: 'number' message: type: 'string' data: responseSchema ;}
see config/config.default.js for more detail.
Example
Define schema
All schemas must defined at app/schema
, and will auto load to app.schema
.
// app/schema/home.jsmoduleexports = 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.jsmoduleexports = index: // ... ; // should match to // app/controller/home.js async { // ... }
Use middleware
This middleware should be placed in front of the controller:
// app/router.jsmodule { const router controller middleware schema = app; const validate = middleware; router;}
see test for more detail.
Questions & Suggestions
Please open an issue here.