simple-body-validator
Version:
This package is inspired by Laravel validation, and aims to make body validation easier for Javascript developers
59 lines (58 loc) • 2.17 kB
JavaScript
;
import { deepFind, deepSet, dotify } from '../utils/object';
const validationData = {
/**
* initialize and gather data for the given attribute.
*/
initializeAndGatherData: function (attribute, masterData) {
let data = dotify(this.initializeAttributeOnData(attribute, masterData));
return Object.assign(Object.assign({}, data), this.extractValuesFromWildCards(masterData, data, attribute));
},
/**
* Gather a copy of the attribute data filled with ant missing attributes.
*/
initializeAttributeOnData: function (attribute, masterData) {
const explicitPath = this.getLeadingExplicitAttributePath(attribute);
let data = this.extractDataFromPath(explicitPath, JSON.parse(JSON.stringify(masterData)));
if (attribute.indexOf('*') === -1 || attribute.indexOf('*') === attribute.length - 1) {
return data;
}
deepSet(data, attribute, null);
return data;
},
/**
* Get all of the exact attribute values for a given wildcard attribute.
*/
extractValuesFromWildCards(masterData, data, attribute) {
let keys = [];
const pattern = new RegExp('^' + attribute.replace(/\*/g, '[^\.]*'));
let result = null;
for (let key in data) {
result = key.match(pattern);
if (result) {
keys.push(result[0]);
}
}
data = {};
keys.forEach(key => data[key] = deepFind(masterData, key));
return data;
},
/**
* Get the explicit part of the attribute name - ex: 'foo.bar.*.baz' -> 'foo.bar'
*/
getLeadingExplicitAttributePath: function (attribute) {
return attribute.split('*')[0].replace(/\.$/, '');
},
/**
* Extract data based on the given dot-notated path.
*/
extractDataFromPath(path, masterData) {
let results = {};
let value = deepFind(masterData, path);
if (value !== undefined) {
deepSet(results, path, value);
}
return results;
}
};
export default validationData;