UNPKG

thinkjs

Version:

ThinkJS - Use full ES6+ features to develop web applications

78 lines (70 loc) 1.99 kB
const Validator = require('think-validator'); const helper = require('think-helper'); const INVOKED = Symbol('invoked'); let validatorsRuleAdd = false; module.exports = { /** * combine scope and rules */ getCombineRules(scope, rules) { if (helper.isObject(scope)) { rules = helper.extend({}, scope, rules); } return rules; }, /** * validate rules */ validate(rules, msgs) { if (helper.isEmpty(rules)) return; this[INVOKED] = true; // add user defined rules if (!validatorsRuleAdd) { validatorsRuleAdd = true; const rules = think.app.validators.rules || {}; for (const key in rules) { Validator.addRule(key, rules[key]); } } const instance = new Validator(this.ctx); msgs = Object.assign({}, think.app.validators.messages, msgs); rules = this.getCombineRules(this.scope, rules); const ret = instance.validate(rules, msgs); if (!helper.isEmpty(ret)) { this.validateErrors = ret; return false; } return true; }, /** * after magic method */ __after() { // This will be removed in the future (>think-logic@1.2.0) // check request method is allowed let allowMethods = this.allowMethods; if (!helper.isEmpty(allowMethods)) { if (helper.isString(allowMethods)) { allowMethods = allowMethods.split(',').map(e => { return e.toUpperCase(); }); } const method = this.method; if (allowMethods.indexOf(method) === -1) { this.fail(this.config('validateDefaultErrno'), 'METHOD_NOT_ALLOWED'); return false; } } // check rules if (!this[INVOKED]) { this.rules = this.getCombineRules(this.scope, this.rules); if (!helper.isEmpty(this.rules)) { const flag = this.validate(this.rules); if (!flag) { this.fail(this.config('validateDefaultErrno'), this.validateErrors); return false; } } } } };