UNPKG

@uni-ts/model

Version:

Utils for creating data models in TypeScript.

53 lines 1.81 kB
import { ModelValidationError } from './error.js'; import { getSyncValidationResult, merge } from './helpers.js'; /** * Creates a type-safe data model based on schema from any Standard Schema compatible validation library. * * @template S - Type of the Standard Schema compatible validation schema * @param schema - A validation schema that follows the Standard Schema interface * @returns A model object with validation utilities * * @example * ```typescript * import { z } from 'zod'; * * type User = InferModelOutput<typeof User>; // { name: string; email: string } * const User = createModel(z.object({ * name: z.string().min(1), * email: z.string().email(), * })); * * const user1 = User.from({ name: 'John', email: 'john@example.com' }); // User * const user2 = User.from({ name: '', email: '' }); // throws ModelValidationError * ``` * * @example * ```typescript * import { z } from 'zod'; * * type Email = InferModelOutput<typeof Email>; // string & z.$brand<'Email'> * const Email = createModel(z.string().email().brand('Email')); * * function sendEmail(email: Email) { * // TypeScript ensures only validated emails can be passed * } * ``` */ export function createModel(schema, extend) { return merge({ schema, is: (value) => !getSyncValidationResult(schema, value).issues, from: (value) => validate(schema, value), cast: (value) => validate(schema, value), }, extend); } export function validate(schema, value) { const result = getSyncValidationResult(schema, value); if (result.issues) { throw new ModelValidationError(result.issues); } return result.value; } export { derive } from './derive.js'; export { ModelValidationError, prettifyError } from './error.js'; //# sourceMappingURL=index.js.map