indicative-compiler
Version:
Indicative compiler to compile parsed schema into highly optimized functions
87 lines (86 loc) • 2.8 kB
JavaScript
"use strict";
/**
* @module compiler/validator
*/
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 pope_1 = require("pope");
const lodash_set_1 = __importDefault(require("lodash.set"));
/**
* Collector collects all the errors and creates a copy of validated
* data (only when `generateTree = true`).
*/
class Collector {
constructor(formatter, generateTree, customErrorCollector) {
this.formatter = formatter;
this.generateTree = generateTree;
this.customErrorCollector = customErrorCollector;
this.tree = {};
this.hasErrors = false;
}
/**
* Set value of a given node. The function results in a noop
* when `value === undefined` or the validation chain has
* one or more errors.
*/
setValue(pointer, value) {
if (!this.generateTree || value === undefined || this.hasErrors) {
return;
}
pointer = pointer.replace('.::tip::', '');
lodash_set_1.default(this.tree, pointer, value);
}
/**
* Returns the collected data
*/
getData() {
return this.tree;
}
/**
* Returns errors from the formatter
*/
getErrors() {
return this.formatter.toJSON();
}
/**
* Passes error to the error formatter for a given field and rule.
* Also when the message is undefined, it will create a generic
* message.
*/
setError(pointer, rule, message) {
this.hasErrors = true;
if (message && typeof (message) === 'string') {
message = pope_1.pope(message, {
field: pointer,
args: rule.args,
validation: rule.name,
});
}
message = message || `${rule.name} validation failed on ${pointer}`;
message = typeof (message) === 'function' ? message(pointer, rule.name, rule.args) : message;
/**
* When custom error collector is defined, then we let it handle then
* error, otherwise we report it to the formatter ourselves
*/
if (typeof (this.customErrorCollector) === 'function') {
this.customErrorCollector(this.formatter, message, pointer, rule.name, rule.args);
}
else {
/**
* Report error to the formatter
*/
this.formatter.addError(message, pointer, rule.name, rule.args);
}
}
}
exports.Collector = Collector;