swaf/src/db/ModelComponent.ts

49 lines
1.5 KiB
TypeScript

import {getMethods} from "../Utils.js";
import Model from "./Model.js";
import {ModelFieldData} from "./ModelQuery.js";
import Validator from "./Validator.js";
export default abstract class ModelComponent<M extends Model> {
protected readonly _model: M;
private readonly _validators: { [K in keyof this]?: Validator<this[K]> } = {};
[key: string]: ModelFieldData;
public constructor(model: M) {
this._model = model;
}
public applyToModel(): void {
this.init?.();
const model = this._model as Model;
for (const property of this._properties) {
if (!property.startsWith('_')) {
model[property] = this[property];
model['_validators'][property] = this._validators[property] as Validator<ModelFieldData> | undefined;
}
}
for (const method of getMethods(this)) {
if (!method.startsWith('_') &&
['init', 'setValidation'].indexOf(method) < 0 &&
model[method] === undefined) {
model[method] = this[method];
}
}
}
protected init?(): void;
protected setValidation<K extends keyof this>(propertyName: K): Validator<this[K]> {
const validator = new Validator<this[K]>();
this._validators[propertyName] = validator;
return validator;
}
private get _properties(): string[] {
return Object.getOwnPropertyNames(this).filter(p => !p.startsWith('_'));
}
}