26 lines
584 B
TypeScript
26 lines
584 B
TypeScript
|
|
export type Validator<T extends Object> = {
|
||
|
|
field: keyof T,
|
||
|
|
errorMsg: string,
|
||
|
|
validationFunc: (obj: T) => boolean
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Ejecuta una lista de validadores en orden, si alguno
|
||
|
|
* falla devuelve un Error
|
||
|
|
*/
|
||
|
|
export class BodyValidator<T extends Object> {
|
||
|
|
validatorList: Validator<T>[] = []
|
||
|
|
constructor(
|
||
|
|
validators: Validator<T>[]
|
||
|
|
) {
|
||
|
|
this.validatorList = validators
|
||
|
|
}
|
||
|
|
|
||
|
|
public validate(obj: T) {
|
||
|
|
for (const validator of this.validatorList) {
|
||
|
|
if (validator.validationFunc(obj) == false) throw new Error(validator.errorMsg)
|
||
|
|
}
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|