egg-validate-schema
v1.0.0
Published
validate by json-schema plugin for egg
Downloads
14
Maintainers
Readme
egg-validate-schema
Validate with JSON Schema
plugin for egg.
see ajv for more information.
Install
$ npm i egg-validate-schema --save
Usage
// {app_root}/config/plugin.js
exports.validateSchema = {
package: 'egg-validate-schema',
};
Config
fully support ajv
options, see document
// {app_root}/config/config.{env}.js
exports.validateSchema = {
// allErrors: true,
// v5: true,
};
Validate Request Body
const jsonSchema = {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"info": {
"type": "object"
}
},
"required": [
"name",
"info"
],
};
exports.create = function* () {
// if validate fail will response 422 status code
this.validateBySchema(jsonSchema);
// pass your own data,default use `this.request.body`
// this.validateBySchema(jsonSchema[, your_data]);
// validate pass
this.body = this.request.body;
};
validate fail response detail:
HTTP/1.1 422 Unprocessable Entity
{
"message": "Validation Failed",
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": { missingProperty: 'name' },
"message": "should have required property 'name'",
}
]
}
Questions & Suggestions
Please open an issue here.