egg-joi
v2.0.1
Published
joi validator
Downloads
231
Readme
egg-joi
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.