guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
58 lines (57 loc) • 2.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperty = void 0;
const createValidationResult_1 = require("./createValidationResult");
const createValidationError_1 = require("./createValidationError");
const createTreeNode_1 = require("./createTreeNode");
const getExpectedTypeName_1 = require("./getExpectedTypeName");
const typeGuardMeta_1 = require("./typeGuardMeta");
const validateObject_1 = require("./validateObject");
const validateArray_1 = require("./validateArray");
/**
* Validate a single property using functional approach
* @param key - The property key to validate
* @param value - The value to validate
* @param typeGuard - The type guard function to use
* @param context - The validation context
* @returns A ValidationResult for this property
*/
const validateProperty = (key, value, typeGuard, context) => {
const propertyPath = `${context.path}.${key}`;
const propertyContext = {
path: propertyPath,
config: context.config || null,
...(context.parentTree && { parentTree: context.parentTree })
};
const errorMode = context.config?.errorMode || 'multi';
const schema = (0, typeGuardMeta_1.getTypeGuardSchema)(typeGuard);
const itemGuard = (0, typeGuardMeta_1.getTypeGuardItemGuard)(typeGuard);
if (errorMode === 'multi' || errorMode === 'json') {
if (schema) {
return (0, validateObject_1.validateObject)(value, schema, propertyContext);
}
if (itemGuard && (0, typeGuardMeta_1.isArrayTypeGuard)(typeGuard)) {
return (0, validateArray_1.validateArray)(value, itemGuard, propertyContext);
}
}
const validateWithConfig = (config) => {
const isValid = typeGuard(value, config);
const expectedType = (0, getExpectedTypeName_1.getExpectedTypeName)(typeGuard);
return isValid
? (0, createValidationResult_1.createValidationResult)(true, [], (0, createTreeNode_1.createTreeNode)(propertyPath, true, expectedType, value))
: (() => {
const error = (0, createValidationError_1.createValidationError)(propertyPath, expectedType, value, `Expected ${propertyPath} (${JSON.stringify(value)}) to be "${expectedType}"`);
const treeNode = (0, createTreeNode_1.createTreeNode)(propertyPath, false, expectedType, value);
treeNode.errors = [error];
return (0, createValidationResult_1.createValidationResult)(false, [error], treeNode);
})();
};
if ((0, typeGuardMeta_1.isNestedObjectTypeGuard)(typeGuard)) {
const nestedConfig = context.config
? { ...context.config, identifier: propertyPath }
: null;
return validateWithConfig(nestedConfig);
}
return validateWithConfig(null);
};
exports.validateProperty = validateProperty;