This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { z } from 'zod'
|
||||
import {z, ZodType} from 'zod'
|
||||
import {InjectionAware} from '../di'
|
||||
import {ErrorWithContext, TypeTag} from '../util'
|
||||
import {ZodifyRecipient} from './ZodifyRecipient'
|
||||
@@ -8,7 +8,7 @@ import {Logging} from '../service/Logging'
|
||||
/** Type tag for a validated runtime type. */
|
||||
export type Valid<T> = TypeTag<'@extollo/lib:Valid'> & T
|
||||
|
||||
export type ValidatorFactory<T extends Validator<T>> = T | (() => T)
|
||||
export type ValidatorFactory<T> = Validator<T> | (() => Validator<T>)
|
||||
|
||||
/**
|
||||
* Error thrown if the schema for a validator cannot be located.
|
||||
@@ -45,8 +45,16 @@ export class ValidationError<T> extends ErrorWithContext {
|
||||
* Validates input data against a schema at runtime.
|
||||
*/
|
||||
export class Validator<T> extends InjectionAware implements ZodifyRecipient {
|
||||
public static fromSchema<T2>(type: ZodType<T2>): Validator<T2> {
|
||||
const inst = new Validator<T2>()
|
||||
inst.schema = type
|
||||
return inst
|
||||
}
|
||||
|
||||
__exZodifiedSchemata: number[] = []
|
||||
|
||||
protected schema?: ZodType<T>
|
||||
|
||||
/**
|
||||
* Parse the input data against the schema.
|
||||
* @throws ValidationError
|
||||
@@ -90,6 +98,10 @@ export class Validator<T> extends InjectionAware implements ZodifyRecipient {
|
||||
|
||||
/** Get the Zod schema. */
|
||||
protected getZod(): z.ZodType<T> {
|
||||
if ( this.schema ) {
|
||||
return this.schema
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
if ( this.__exZodifiedSchemata.length < 1 ) {
|
||||
throw new InvalidSchemaMappingError()
|
||||
|
||||
Reference in New Issue
Block a user