|
| 1 | +import { type Schema as JoiSchema } from 'joi'; |
| 2 | +import { type ZodType } from 'zod'; |
| 3 | +import { type ValidationSchema } from '../interfaces/validation-schema.interface'; |
| 4 | +import { Validator } from './abstract.validator'; |
| 5 | +import { JoiValidator } from './joi.validator'; |
| 6 | +import { ZodValidator } from './zod.validator'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Factory for creating validation schemas |
| 10 | + * @publicApi |
| 11 | + */ |
| 12 | +export class ValidatorFactory { |
| 13 | + /** |
| 14 | + * Creates a Joi validator |
| 15 | + * @param schema Joi schema |
| 16 | + * @returns JoiValidator instance |
| 17 | + */ |
| 18 | + static createJoiValidator(schema: JoiSchema): Validator { |
| 19 | + return new JoiValidator(schema); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Creates a Zod validator |
| 24 | + * @param schema Zod schema |
| 25 | + * @returns ZodValidator instance |
| 26 | + */ |
| 27 | + static createZodValidator(schema: ZodType): Validator { |
| 28 | + return new ZodValidator(schema); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Creates a validator from a schema object |
| 33 | + * Automatically detects the schema type based on the schema object |
| 34 | + * @param schema Schema object (Joi or Zod) |
| 35 | + * @returns ValidationSchema instance |
| 36 | + */ |
| 37 | + static createValidator(schema: ValidationSchema): Validator { |
| 38 | + // Check if it's a validator instance |
| 39 | + if (schema instanceof Validator) { |
| 40 | + return schema; |
| 41 | + } |
| 42 | + |
| 43 | + // Check if it's a Joi schema first |
| 44 | + if ( |
| 45 | + schema && |
| 46 | + typeof schema === 'object' && |
| 47 | + 'validate' in schema && |
| 48 | + typeof schema.validate === 'function' |
| 49 | + ) { |
| 50 | + return this.createJoiValidator(schema as JoiSchema); |
| 51 | + } |
| 52 | + |
| 53 | + // Check if it's a Zod schema |
| 54 | + if ( |
| 55 | + schema && |
| 56 | + typeof schema === 'object' && |
| 57 | + 'parse' in schema && |
| 58 | + typeof schema.parse === 'function' |
| 59 | + ) { |
| 60 | + return this.createZodValidator(schema as ZodType); |
| 61 | + } |
| 62 | + |
| 63 | + throw new Error( |
| 64 | + 'Unsupported schema type. Please use Joi or Zod schema or implement the validator directly.', |
| 65 | + ); |
| 66 | + } |
| 67 | +} |
0 commit comments