/egg-validate-middleware

JSON schema validator middleware for Egg.js.

Primary LanguageJavaScriptMIT LicenseMIT

egg-validate-middleware

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

JSON schema validator middleware for Egg.js.

Install

$ npm i egg-validate-middleware --save

Usage

// {app_root}/config/plugin.js
exports.validateMiddleware = {
  enable: true,
  package: 'egg-validate-middleware',
};

Configuration

// {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.

Example

Define schema

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';
  }
}

Use middleware

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.

Questions & Suggestions

Please open an issue here.

License

MIT