UNPKG

simple-body-validator

Version:

This package is inspired by Laravel validation, and aims to make body validation easier for Javascript developers

60 lines (59 loc) 2.29 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); const object_1 = require("../utils/object"); const validationData = { /** * initialize and gather data for the given attribute. */ initializeAndGatherData: function (attribute, masterData) { let data = (0, object_1.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; } (0, object_1.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] = (0, object_1.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 = (0, object_1.deepFind)(masterData, path); if (value !== undefined) { (0, object_1.deepSet)(results, path, value); } return results; } }; exports.default = validationData;