guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
55 lines (54 loc) • 2.79 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");
/**
* 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 })
};
// Unified validation function to avoid duplicate checks
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);
})();
};
// Use functional approach to handle nested vs regular type guards
const validateNestedTypeGuard = () => {
// In multi mode, don't pass config to avoid duplicate error reporting
// Let the validation utils handle all error reporting
const errorMode = context.config?.errorMode || 'multi';
const nestedConfig = (context.config && errorMode !== 'multi') ? {
...context.config,
identifier: propertyPath
} : null;
return validateWithConfig(nestedConfig);
};
const validateRegularTypeGuard = () => {
// Don't pass config to avoid duplicate callbacks when using validation utils
return validateWithConfig(null);
};
// Use functional composition to determine validation strategy
return !typeGuard.name ? validateNestedTypeGuard() : validateRegularTypeGuard();
};
exports.validateProperty = validateProperty;