export class ModelTemplateCombine { readonly type: ArrayCombine['type'] readonly models: T public readonly validations: Set<(value: typeof this.type) => Promise> public readonly filters: Set<(value: Model.RemoveTypesForFilter) => ArrayCombine['type']> constructor(models: T) { this.models = models this.validations = new Set() this.filters = new Set() } public addValidation(callback: (value: typeof this.type) => Promise) { this.validations.add(callback) } public addFilters(callback: (value: Model.RemoveTypesForFilter) => Model.RemoveTypesForFilter) { this.filters.add(callback) } public filter(obj: any): any { let value = obj for (let i = 0; i < this.models.length; i++) { const model = this.models[i] if (model.filter !== undefined) { value = model.filter(value) } } this.filters.forEach(f => { value = f(value)}) return value } public async validate(obj: any, skipFilter?: true): Promise> { let v = obj if (!skipFilter) { v = this.filter(v) } { // Valida as models const promises: Promise<{ errors?: PlataError[] }>[] = [] for (let i = 0; i < this.models.length; i++) { const model = this.models[i]; promises.push(Plata.FastPromise(() => model.validate(v, true))) } const results = await Promise.all(promises) const errors = results .filter((r): r is { errors: PlataError[] } => r.errors !== undefined) .flatMap(r => r.errors) ; if (errors.length !== 0) { return { value: undefined, errors } } } { // Validacoes adicionais const promises: Promise[] = [] this.validations.forEach(va => promises.push( Plata.FastPromise(() => va(v)) ) ) const result = await Promise.all(promises) const errors = result.filter(Boolean) if (errors.length !== 0) { return { errors, value: undefined } } } return { value: v, errors: undefined } } }