swaf/src/db/ModelComponent.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

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