2021-05-03 19:29:22 +02:00
|
|
|
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
|
|
|
|
2020-09-25 23:42:15 +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
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
[key: string]: ModelFieldData;
|
2020-07-24 12:13:28 +02:00
|
|
|
|
2020-09-25 23:42:15 +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 {
|
2020-09-25 22:03:22 +02:00
|
|
|
this.init?.();
|
2020-07-26 11:37:01 +02:00
|
|
|
|
2020-09-25 23:42:15 +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('_')) {
|
2020-09-25 23:42:15 +02:00
|
|
|
model[property] = this[property];
|
2020-11-15 14:13:35 +01:00
|
|
|
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 &&
|
2020-09-25 23:42:15 +02:00
|
|
|
model[method] === undefined) {
|
|
|
|
model[method] = this[method];
|
2020-07-26 11:37:01 +02:00
|
|
|
}
|
|
|
|
}
|
2020-07-24 12:13:28 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
protected init?(): void;
|
2020-07-26 11:37:01 +02:00
|
|
|
|
2020-09-25 23:42:15 +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('_'));
|
|
|
|
}
|
|
|
|
}
|