swaf/src/db/ModelComponent.ts

47 lines
1.3 KiB
TypeScript
Raw Normal View History

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