egg-validate-schema

1.0.0 • Public • Published

egg-validate-schema

NPM version build status Test coverage David deps Known Vulnerabilities npm download

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.

License

MIT

Package Sidebar

Install

npm i egg-validate-schema

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • mansonchor