egg-joi
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

egg-joi

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

Install

$ npm i egg-joi --save

Usage

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

Configuration

// {app_root}/config/config.default.js
exports.joi = {
    options: {},
    locale: {
        'zh-cn': {}
    },
    throw: true, // throw immediately when capture exception
    throwHandle: (error) => { return error; }, // error message format when throw is true
    errorHandle: (error) => { return error; }, // error message format when throw is false
    resultHandle: (result) => { return result; } // fromat result
};

see config/config.default.js for more detail.

Example

app/validator/sessions

    'use strict';
 
    module.exports = app => {
        const Joi = app.Joi;
        return {
            login: Joi.object().keys({
                email: Joi.string().email(),
                password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)
            })
        }
    };

app/controller/sessions

    'use strict';
 
    module.exports = app => {
      class SessionsController extends app.Controller {
        * login() {
          this.ctx.validate(app.validator.sessions.login);
          // this.ctx.validate(app.validator.sessions.login, this.ctx.request.body);
          // this.ctx.validate(app.validator.sessions.login, this.ctx.request.body, {abortEarly: false}); see [joi] https://github.com/hapijs/joi/blob/v11.0.1/API.md
          // let {error, value} = this.ctx.validate(app.validator.sessions.login, false);
          // let {error, value} = this.ctx.validate(app.validator.sessions.login, this.ctx.request.body, false);
          // let {error, value} = this.ctx.validate(app.validator.sessions.login, this.ctx.request.body, {abortEarly: false}, false);
 
          this.body = 'hello';
        }
      }
      return SessionsController;
    };

Questions & Suggestions

Please open an issue here.

License

MIT

Package Sidebar

Install

npm i egg-joi

Weekly Downloads

50

Version

2.0.1

License

MIT

Unpacked Size

10.7 kB

Total Files

9

Last publish

Collaborators

  • leaf