import { z } from 'zod' import Response, { ResponseErrorType } from '../API/Response.js' import Globals from '../Globals.js' /** * Validates the given data against the provided schema. * @param {any} data - The data to be validated. * @param {z.ZodObject | z.ZodUnion | z.ZodIntersection | z.ZodEffects} schema - The schema to validate against. * @returns {boolean | Response} - Returns true if the data is valid, otherwise returns a response object with an error message. */ export default class Validator { /** * Validates the given data against the provided schema. * @param {any} data - The data to be validated. * @param {z.ZodObject | z.ZodUnion | z.ZodIntersection | z.ZodEffects} schema - The schema to validate against. * @returns {boolean | Response} - Returns either true if the data is valid or a Response object with an error message if validation fails. */ public static validateSchema( data: any, schema: z.ZodObject | z.ZodUnion | z.ZodIntersection | z.ZodEffects ): boolean | Response { let error, validatedInput // Validate body against known zod schema try { schema.parse(data) validatedInput = true } catch (err: z.ZodError | any) { if (err instanceof z.ZodError) error = JSON.parse(err.message) else error = 'Unknown validation error!' //unhandled case, hard to test } // Error validation if (!validatedInput || error) { return Response.BadRequestResponse( Globals.ErrorResponseValidationFail, Globals.ErrorCode_InvalidInput, { validationFailure: error } ) } else { return true } } }