2026-03-04 13:51:24 +01:00
|
|
|
import { Result } from "../domain/Result.js"
|
|
|
|
|
|
2026-02-10 15:57:03 +01:00
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-04 13:51:24 +01:00
|
|
|
public validate(obj: T): Result<{ msg: string, field: string }, boolean> {
|
2026-02-10 15:57:03 +01:00
|
|
|
for (const validator of this.validatorList) {
|
2026-03-04 13:51:24 +01:00
|
|
|
if (validator.validationFunc(obj) == false)
|
|
|
|
|
return {
|
|
|
|
|
error: {
|
|
|
|
|
msg: validator.errorMsg,
|
|
|
|
|
field: String(validator.field)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-10 15:57:03 +01:00
|
|
|
}
|
2026-03-04 13:51:24 +01:00
|
|
|
return {
|
|
|
|
|
data: true
|
|
|
|
|
};
|
2026-02-10 15:57:03 +01:00
|
|
|
}
|
|
|
|
|
}
|