indicative-compiler
Version:
Indicative compiler to compile parsed schema into highly optimized functions
90 lines (89 loc) • 2.93 kB
JavaScript
"use strict";
/**
* @module compiler/sanitizer
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* indicative-compiler
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const lodash_get_1 = __importDefault(require("lodash.get"));
/**
* Wraps an array of [[SanitizationsRunner]] and executes
* them based upon the length of an data array at runtime.
*/
class ArrayWrapper {
constructor(field, index, childSanitizations, dotPath) {
this.field = field;
this.index = index;
this.childSanitizations = childSanitizations;
this.dotPath = dotPath;
/**
* The pointer to read the value of the field inside the data tip
*/
this.pointer = this.dotPath.concat(this.field).join('.');
}
/**
* Returns data copy to the passed to all the children of the array.
*/
getDataCopy(data) {
const value = lodash_get_1.default(data.tip, this.pointer);
/**
* Ensure value is array, otherwise skip the sanitization process.
*/
if (!Array.isArray(value)) {
return null;
}
/**
* Since we are adding new properties to the data object. We have
* to create a new copy, otherwise the array specific values
* will leak this info to other sanitizations as well.
*/
return {
original: data.original,
tip: null,
parentArray: value,
currentIndex: this.index === '*' ? 0 : Number(this.index),
};
}
/**
* Executes all sanitizations for a given index value inside the array.
*/
executeSanitizations(data, config) {
this.childSanitizations.forEach((sanitization) => sanitization.exec(data, config));
}
/**
* Execute series of sanitizations for values inside an array
*/
exec(data, config) {
const dataCopy = this.getDataCopy(data);
if (!dataCopy) {
return;
}
/**
* If index is a not a wildcard, then we run validations
* just for the given index.
*/
if (this.index !== '*') {
dataCopy.tip = dataCopy.parentArray[dataCopy.currentIndex];
return this.executeSanitizations(dataCopy, config);
}
/**
* Loop over all the entire array and execute validations
* for each field.
*/
dataCopy.parentArray.forEach((item, index) => {
dataCopy.tip = item;
dataCopy.currentIndex = index;
this.executeSanitizations(dataCopy, config);
});
}
}
exports.ArrayWrapper = ArrayWrapper;