UNPKG

rule-filter-validator

Version:

A object and scope validator based on structured rules

48 lines 2.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculatePayloadFunctions = calculatePayloadFunctions; const lodash_es_1 = require("lodash-es"); const functions_js_1 = require("./functions.js"); /** * Inject function output fields into a given payload for accurate validation * * @param payload Any data payload * @param filter A single level filter rule to verify against * * @example * ```js * const input = { date: '2022-03-29T11:37:56Z' }; * const filter = { 'year(date)': { _eq: 2022 }} * const output = applyFunctions(input, filter); * // { date: '2022-03-29T11:37:56Z', 'year(date)': 2022 } * ``` */ function calculatePayloadFunctions(payload, filter) { processFilterLevel(filter); return payload; function processFilterLevel(filter, parentPath) { for (const [key, value] of Object.entries(filter)) { const path = parentPath ? parentPath + '.' + key : key; if (key.startsWith('_') === false && (0, lodash_es_1.isPlainObject)(value)) { processFilterLevel(value, path); } if (Array.isArray(value) && (key === '_and' || key === '_or')) { for (const filter of value) { processFilterLevel(filter, parentPath); } continue; } if (key.includes('(') && key.includes(')')) { const functionName = key.split('(')[0]; const fieldKey = key.match(/\(([^)]+)\)/)?.[1]; if (!fieldKey || !functionName) continue; const currentValuePath = parentPath ? parentPath + '.' + fieldKey : fieldKey; const currentValue = (0, lodash_es_1.get)(payload, currentValuePath); const currentPayloadPath = parentPath ? parentPath + '.' + key : key; (0, lodash_es_1.set)(payload, currentPayloadPath, functions_js_1.functions[functionName](currentValue)); } } } } //# sourceMappingURL=calculate-payload-functions.js.map