UNPKG

veffect

Version:

powerful TypeScript validation library built on the robust foundation of Effect combining exceptional type safety, high performance, and developer experience. Taking inspiration from Effect's functional principles, VEffect delivers a balanced approach tha

109 lines (108 loc) 5.27 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.discriminatedUnion = discriminatedUnion; const E = __importStar(require("../internal/effect")); const errors_1 = require("../errors"); /** * Creates a discriminated union schema that validates and handles union types based on a discriminator property * * @param discriminator The property that determines which schema to use * @param schemas Array of object schemas that each have the discriminator property * @returns A schema that validates against the appropriate union member based on the discriminator * * @example * const userSchema = discriminatedUnion('type', [ * object({ type: literal('admin'), permissions: array(string()) }), * object({ type: literal('user'), role: string() }) * ]); */ function discriminatedUnion(discriminator, schemas) { // Validate that all schemas have the discriminator property for (const schema of schemas) { if (schema._tag !== 'ObjectSchema') { throw new Error(`All schemas in a discriminated union must be object schemas, but found: ${schema._tag}`); } } const schema = { _tag: 'DiscriminatedUnionSchema', toValidator: () => ({ validate: (input, options) => { if (input === null || input === undefined || typeof input !== 'object' || Array.isArray(input)) { return E.fail(new errors_1.TypeValidationError(`Expected an object for discriminated union`, 'object', typeof input, options === null || options === void 0 ? void 0 : options.path)); } // Check if the input has the discriminator property const discriminatorValue = input[discriminator]; if (discriminatorValue === undefined) { return E.fail(new errors_1.TypeValidationError(`Expected object with '${discriminator}' property for discriminated union`, `object with '${discriminator}' property`, `object without '${discriminator}' property`, options === null || options === void 0 ? void 0 : options.path)); } // Try each schema and collect errors const errors = []; for (const schema of schemas) { const validator = schema.toValidator(); const result = validator.validate(input, options); // Check if this schema succeeded with the input const resultEither = E.runSync(E.either(result)); if (E.isRight(resultEither)) { return result; // Found a matching schema } else { errors.push(resultEither.left); } } // If we get here, none of the schemas matched return E.fail(new errors_1.UnionValidationError(`No schema matched for discriminated union with '${discriminator}' value: ${discriminatorValue}`, errors, options === null || options === void 0 ? void 0 : options.path)); }, parse: (input) => { const result = E.runSync(E.either(schema.toValidator().validate(input))); if (E.isLeft(result)) { throw result.left; } return result.right; }, safeParse: (input) => { const result = E.runSync(E.either(schema.toValidator().validate(input))); if (E.isLeft(result)) { return { success: false, error: result.left }; } return { success: true, data: result.right }; }, validateAsync: async (input, options) => { return E.unwrapEither(E.runSync(E.either(schema.toValidator().validate(input, options)))); } }) }; return schema; }