Thin MongoDB ODM built for Standard Schema
mongodb zod deno
1import type { z } from "@zod/zod"; 2import type { Schema, Infer, Input } from "../types.ts"; 3import { ValidationError, AsyncValidationError } from "../errors.ts"; 4 5/** 6 * Validate data for insert operations using Zod schema 7 * 8 * @param schema - Zod schema to validate against 9 * @param data - Data to validate 10 * @returns Validated and typed data 11 * @throws {ValidationError} If validation fails 12 * @throws {AsyncValidationError} If async validation is detected 13 */ 14export function parse<T extends Schema>(schema: T, data: Input<T>): Infer<T> { 15 const result = schema.safeParse(data); 16 17 // Check for async validation 18 if (result instanceof Promise) { 19 throw new AsyncValidationError(); 20 } 21 22 if (!result.success) { 23 throw new ValidationError(result.error.issues, "insert"); 24 } 25 return result.data as Infer<T>; 26} 27 28/** 29 * Validate partial data for update operations using Zod schema 30 * 31 * @param schema - Zod schema to validate against 32 * @param data - Partial data to validate 33 * @returns Validated and typed partial data 34 * @throws {ValidationError} If validation fails 35 * @throws {AsyncValidationError} If async validation is detected 36 */ 37export function parsePartial<T extends Schema>( 38 schema: T, 39 data: Partial<z.infer<T>>, 40): Partial<z.infer<T>> { 41 const result = schema.partial().safeParse(data); 42 43 // Check for async validation 44 if (result instanceof Promise) { 45 throw new AsyncValidationError(); 46 } 47 48 if (!result.success) { 49 throw new ValidationError(result.error.issues, "update"); 50 } 51 return result.data as Partial<z.infer<T>>; 52} 53 54/** 55 * Validate data for replace operations using Zod schema 56 * 57 * @param schema - Zod schema to validate against 58 * @param data - Data to validate 59 * @returns Validated and typed data 60 * @throws {ValidationError} If validation fails 61 * @throws {AsyncValidationError} If async validation is detected 62 */ 63export function parseReplace<T extends Schema>(schema: T, data: Input<T>): Infer<T> { 64 const result = schema.safeParse(data); 65 66 // Check for async validation 67 if (result instanceof Promise) { 68 throw new AsyncValidationError(); 69 } 70 71 if (!result.success) { 72 throw new ValidationError(result.error.issues, "replace"); 73 } 74 return result.data as Infer<T>; 75}