UNPKG

@orchestrated-io/cqrs-domain

Version:

Node-cqrs-domain is a node.js module based on node-eventstore. It can be very useful as domain component if you work with (d)ddd, cqrs, eventdenormalizer, host, etc.

64 lines (50 loc) 1.69 kB
var debug = require('debug')('domain:validator'), _ = require('lodash'), tv4Module = require('tv4'), ValidationError = require('./errors/validationError'); /** * Returns a validator function. * @param {Object} options The options object. * @param {Object} schema The schema object. * @returns {Function} */ function getValidator (options, schema) { options = options || {}; options.schemas = options.schemas || {}; options.formats = options.formats || {}; if (!schema || !_.isObject(schema)) { var err = new Error('Please pass a valid schema!'); debug(err); throw err; } var tv4 = tv4Module.freshApi(); _.each(options.schemas, function (v, k) { tv4.addSchema(k, v); }); tv4.addFormat(options.formats); return function (data) { var validation = tv4.validateMultiple(data, schema); if (validation.missing.length > 0) { var missingString = validation.missing[0]; for (var m = 1, lenM = validation.missing.length; m < lenM; m++) { missingString += ', ' + validation.missing[m]; } var err = new Error('Validation schema(s) "' + missingString + '" missing!'); debug(err); return err; } if (!validation.valid) { var errors = validation.errors.map(function (error) { if (error.message.indexOf('not match any schemas') >= 0 && error.subErrors && error.subErrors.length > 0) { return error.subErrors[0]; } else { return error; } }); var firstError = errors[0]; return new ValidationError(firstError.dataPath + ' => ' + firstError.message, errors); } return null; }; } module.exports = getValidator;