import { ModelsInternals } from "./tools" export class ModelTemplate> { public readonly template: T public readonly converters: C | {} public readonly validations: Model.ModelTemplateValidation[] public readonly filters: Set> public readonly type: Model.ExtractTemplateType constructor(template: T, converters: C | {}) { this.template = template this.converters = converters this.validations = new Array() this.filters = new Set() } public trimModel() { this.filters.add(Plata.trimObject) } public addValidation(nome: string, callback: Model.ModelTemplateValidation) { this.validations.push(callback) } public addFilter(nome: string, callback: Model.ModelTemplateFilter) { this.filters.add(callback) } public convert: Model.ModelConvertFuntion = (value, to) => { const c: Model.ConvertFunction | undefined = this.converters[to as string] if (c === undefined) return { errorID: 'BPLM0002', msg: 'Invalid Converter', error: to } ; try { return c(value) } catch (e) { return { errorID: 'BPLM0003', msg: 'Unexpected converter error', error: e } } } public filter(value: any) { if (!value) { value = {} } let v = ModelsInternals.filterTemplate(value, this.template) this.filters.forEach(f => { v = f(v) }) return v } public async validate(value: any, skipFilter?: true): Promise> { const v = skipFilter ? value : this.filter(value) const errors = await ModelsInternals.validateTemplate(v, this.template) if (errors.errorID !== undefined) { return { value: v as any, errors: [errors] } } if (errors.length !== 0) { return { value: v as any, errors } } const promises: Promise[] = new Array(this.validations.length) for (let i = 0; i < this.validations.length; i++) { promises[i] = Plata.FastPromise(() => this.validations[i](v as any)) } const result: PlataResult = await Plata.FastPromise(() => Promise.all(promises)).then( r => ([] as Model.ValidateReturn[]).concat(...r).filter(v => v !== null), err => { return { errorID: 'BPLM0002', msg: `unexpected error while validating model`, error: err } } ) as any if (result.errorID !== undefined) { return { value: v as any, errors: [result] } } return { value: v as any, errors: result.length !== 0 ? result : undefined } } }