UNPKG

@incdevco/framework

Version:
124 lines (65 loc) 2.62 kB
var Promise = require('bluebird'); function Validator(config) { 'use strict'; config = config || {}; this.arrayOf = config.arrayOf || false; this.required = config.required || false; this.validators = config.validators || []; } Validator.prototype.validate = function (input) { 'use strict'; var self = this; return Promise.try(function () { var promise = Promise.resolve(true); if (self.required && (input === undefined || input === null)) { throw new Error('Required'); } if (input) { if (Array.isArray(self.validators)) { if (self.arrayOf) { if (Array.isArray(input)) { input.forEach(function (item, index) { self.validators.forEach(function(validator) { promise = promise.then(function () { return validator.validate(item, input) .catch(function (exception) { exception.index = index; throw exception; }); }); }); }); } else { throw new Error('Must Be An Array'); } } else { self.validators.forEach(function(validator) { promise = promise.then(function () { return validator.validate(input, input); }); }); } } else { Object.keys(input).forEach(function (key) { if (!self.validators[key]) { var exception = new Error('Not Allowed'); exception.key = key; throw exception; } }); Object.keys(self.validators).forEach(function (key) { promise = promise.then(function () { return self.validators[key].validate(input[key], input) .catch(function (exception) { exception.key = key; throw exception; }); }); }); } } return promise; }); }; module.exports = Validator;