UNPKG

rest-api-starter

Version:
59 lines (50 loc) 2.02 kB
/** * Created by svinci on 8/24/16. */ 'use strict'; const Promise = require('bluebird'); const SchemaValidator = require('jsonschema').Validator; const schemaValidator = new SchemaValidator(); /** * Validator builder. * @param schema JSON schema compliant object which will define the validated structure. * @param customValidations Custom validations to be made. (schema, object, id, errors, finishValidation) => void. * The fifth parameter (finishValidation) is a function that must be called once custom validations ended. */ const validator = (schema, customValidations) => ({ 'validate': (object, id) => new Promise((resolve, reject) => { const errors = []; schemaValidator.validate(object, schema).errors.forEach((err) => { if (err.name === 'additionalProperties') { const validationErrorMessage = `validation.error.${schema.description}.schema.unknown.property`; if (errors.indexOf(validationErrorMessage) < 0) { errors.push(validationErrorMessage); } } else { errors.push(`validation.error.${schema.description}.schema.${err.property}`); } }); if (id && !object.id) { errors.push(`validation.error.${schema.description}.schema.instance.id`); } else if (id && id !== object.id) { errors.push(`validation.error.${schema.description}.id.match`); } const finishValidation = () => { if (errors.length === 0) { resolve(object); } else { const errorResponse = { 'name': 'validation.error', 'errors': errors }; reject(errorResponse); } }; if (customValidations) { customValidations(schema, object, id, errors, finishValidation); } else { finishValidation(); } }) }); module.exports = validator;