UNPKG

tyntec-sdk

Version:

TypeScript SDK for Tyntec Conversations API V3

89 lines (88 loc) 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.schemaRegistry = exports.SchemaRegistry = void 0; exports.registerSchemas = registerSchemas; /** * A singleton registry for managing Zod schemas. * This class provides a centralized way to store and retrieve Zod validation schemas. */ class SchemaRegistry { constructor() { this.schemas = new Map(); } /** * Gets the singleton instance of SchemaRegistry. * @returns The singleton instance of SchemaRegistry */ static getInstance() { if (!SchemaRegistry.instance) { SchemaRegistry.instance = new SchemaRegistry(); } return SchemaRegistry.instance; } /** * Registers a new schema with the given name. * @param name - The unique identifier for the schema * @param schema - The Zod schema to register */ registerSchema(name, schema) { this.schemas.set(name, schema); } /** * Retrieves a schema by its name. * @param name - The name of the schema to retrieve * @returns The Zod schema * @throws {Error} If the schema is not found */ getSchema(name) { const schema = this.schemas.get(name); if (!schema) { throw new Error(`Schema not found: ${name}`); } return schema; } /** * Returns a copy of all registered schemas. * @returns A Map containing all registered schemas */ getAllSchemas() { return new Map(this.schemas); } /** * Validates data against a registered schema. * @param name - The name of the schema to use for validation * @param data - The data to validate * @returns The validated and typed data * @throws {z.ZodError} If validation fails */ validate(name, data) { const schema = this.getSchema(name); return schema.parse(data); } /** * Safely validates data against a registered schema without throwing errors. * @param name - The name of the schema to use for validation * @param data - The data to validate * @returns An object containing the validation result and either the validated data or error */ safeValidate(name, data) { const schema = this.getSchema(name); const result = schema.safeParse(data); if (result.success) { return { success: true, data: result.data }; } return { success: false, error: result.error }; } } exports.SchemaRegistry = SchemaRegistry; // Export singleton instance exports.schemaRegistry = SchemaRegistry.getInstance(); /** * Helper function to register multiple schemas at once. * @param schemas - Array of objects containing schema names and their corresponding Zod schemas */ function registerSchemas(schemas) { schemas.forEach(({ name, schema }) => { exports.schemaRegistry.registerSchema(name, schema); }); }