UNPKG

@speakr/speakr-module-services

Version:
69 lines (60 loc) 1.76 kB
'use strict'; const Joi = require('joi'); /** * Writes value to the path on the specified Object. * @param {Object} obj The object to modify. * @param {String} path The path on the object to write to. * @param {Object} value The value to write to the object. * @return {Object} The updated object. */ const writeObject = (obj, path, value) => { const paths = path.split('.'); return paths.reduce((response, key, i) => { if ((key in response) === false) { if (paths.length === i + 1) { response[key] = value; return obj; } response[key] = {}; } return response[key]; }, obj); }; /** * @name validate * @description Validates the data against the schema. * @return {Promise} */ module.exports = (data) => { return { against: (schema, map) => { return new Promise((resolve, reject) => { console.log("here >>>>> ", data, schema); Joi.validate(data, schema, { convert: true, abortEarly: false, allowUnknown: true, skipFunctions: true }, (err) => { console.log('#err',err); if (err) { //@info Generate the error message let message = err.details.map((detail) => { return detail.message; }).join(', '); const error = map ? map(message) : message = { message: message }; error.details = {}; err.details.reduce((result, detail) => { return writeObject(result, detail.path, detail.message); }, error.details); //@info Return the error return reject(error); } return resolve(); }); }); } }; };