2020-09-25 23:42:15 +02:00
|
|
|
import MysqlConnectionManager, {isQueryVariable, query, QueryVariable} from "./MysqlConnectionManager";
|
2020-04-22 15:52:17 +02:00
|
|
|
import Validator from "./Validator";
|
|
|
|
import {Connection} from "mysql";
|
2020-07-24 12:13:28 +02:00
|
|
|
import ModelComponent from "./ModelComponent";
|
|
|
|
import {Type} from "../Utils";
|
2020-09-25 23:42:15 +02:00
|
|
|
import ModelFactory, {PrimaryKeyValue} from "./ModelFactory";
|
2020-07-24 12:13:28 +02:00
|
|
|
import ModelRelation from "./ModelRelation";
|
2020-09-25 23:42:15 +02:00
|
|
|
import ModelQuery, {ModelFieldData, ModelQueryResult, SelectFields} from "./ModelQuery";
|
2020-04-22 15:52:17 +02:00
|
|
|
import {Request} from "express";
|
2020-09-25 22:03:22 +02:00
|
|
|
import Extendable from "../Extendable";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default abstract class Model implements Extendable<ModelComponent<Model>> {
|
2020-07-27 10:53:46 +02:00
|
|
|
public static get table(): string {
|
2020-09-25 23:42:15 +02:00
|
|
|
const single = this.name
|
|
|
|
.replace(/(?:^|\.?)([A-Z])/g, (x, y) => '_' + y.toLowerCase())
|
|
|
|
.replace(/^_/, '');
|
|
|
|
return single + 's';
|
2020-07-27 10:53:46 +02:00
|
|
|
}
|
|
|
|
|
2020-09-06 10:23:32 +02:00
|
|
|
public static getPrimaryKeyFields(): string[] {
|
|
|
|
return ['id'];
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static create<M extends Model>(this: ModelType<M>, data: Pick<M, keyof M>): M {
|
2020-09-06 10:43:45 +02:00
|
|
|
return ModelFactory.get(this).create(data, true);
|
2020-07-27 10:52:39 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static select<M extends Model>(this: ModelType<M>, ...fields: SelectFields): ModelQuery<M> {
|
2020-07-24 12:13:28 +02:00
|
|
|
return ModelFactory.get(this).select(...fields);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static update<M extends Model>(this: ModelType<M>, data: Pick<M, keyof M>): ModelQuery<M> {
|
2020-07-24 12:13:28 +02:00
|
|
|
return ModelFactory.get(this).update(data);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static delete<M extends Model>(this: ModelType<M>): ModelQuery<M> {
|
2020-07-24 12:13:28 +02:00
|
|
|
return ModelFactory.get(this).delete();
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static async getById<M extends Model>(this: ModelType<M>, ...id: PrimaryKeyValue[]): Promise<M | null> {
|
|
|
|
return await ModelFactory.get(this).getById(...id);
|
2020-06-04 14:59:23 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public static async paginate<M extends Model>(
|
|
|
|
this: ModelType<M>,
|
|
|
|
request: Request,
|
|
|
|
perPage: number = 20,
|
|
|
|
query?: ModelQuery<M>,
|
|
|
|
): Promise<ModelQueryResult<M>> {
|
|
|
|
return await ModelFactory.get(this).paginate(request, perPage, query);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
protected readonly _factory: ModelFactory<Model>;
|
|
|
|
private readonly _components: ModelComponent<this>[] = [];
|
2020-09-25 23:42:15 +02:00
|
|
|
private readonly _validators: { [K in keyof this]?: Validator<this[K]> | undefined } = {};
|
2020-09-06 10:43:45 +02:00
|
|
|
private _exists: boolean;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
[key: string]: ModelFieldData;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public constructor(factory: ModelFactory<never>, isNew: boolean) {
|
|
|
|
if (!(factory instanceof ModelFactory)) throw new Error('Cannot instantiate model directly.');
|
2020-07-24 15:40:10 +02:00
|
|
|
this._factory = factory;
|
2020-09-25 23:42:15 +02:00
|
|
|
this.init?.();
|
2020-09-06 10:43:45 +02:00
|
|
|
this._exists = !isNew;
|
2020-06-04 14:59:23 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
protected init?(): void;
|
2020-07-24 12:13:28 +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;
|
2020-06-04 14:59:23 +02:00
|
|
|
}
|
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
public addComponent(modelComponent: ModelComponent<this>): void {
|
2020-07-26 11:37:01 +02:00
|
|
|
modelComponent.applyToModel();
|
2020-07-24 12:13:28 +02:00
|
|
|
this._components.push(modelComponent);
|
|
|
|
}
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
public as<C extends ModelComponent<Model>>(type: Type<C>): C {
|
2020-07-24 12:13:28 +02:00
|
|
|
for (const component of this._components) {
|
|
|
|
if (component instanceof type) {
|
2020-09-25 22:03:22 +02:00
|
|
|
return this as unknown as C;
|
2020-07-24 12:13:28 +02:00
|
|
|
}
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
2020-09-25 22:03:22 +02:00
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
throw new Error(`Component ${type.name} was not initialized for this ${this.constructor.name}.`);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
public asOptional<C extends ModelComponent<Model>>(type: Type<C>): C | null {
|
|
|
|
for (const component of this._components) {
|
|
|
|
if (component instanceof type) {
|
|
|
|
return this as unknown as C;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public updateWithData(data: Pick<this, keyof this> | Record<string, unknown>): void {
|
2020-07-24 12:13:28 +02:00
|
|
|
for (const property of this._properties) {
|
|
|
|
if (data[property] !== undefined) {
|
2020-09-25 23:42:15 +02:00
|
|
|
this[property] = data[property] as this[keyof this & string];
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-28 14:16:06 +02:00
|
|
|
/**
|
|
|
|
* Override this to automatically fill obvious missing data i.e. from relation or default value that are fetched
|
|
|
|
* asynchronously.
|
|
|
|
*/
|
2020-09-25 22:03:22 +02:00
|
|
|
protected async autoFill?(): Promise<void>;
|
2020-08-28 14:16:06 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
protected async beforeSave?(connection: Connection): Promise<void>;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
protected async afterSave?(): Promise<void>;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
public async save(connection?: Connection, postHook?: (callback: () => Promise<void>) => void): Promise<void> {
|
2020-09-06 10:43:45 +02:00
|
|
|
if (connection && !postHook) throw new Error('If connection is provided, postHook must be provided too.');
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
await this.autoFill?.();
|
2020-04-22 15:52:17 +02:00
|
|
|
await this.validate(false, connection);
|
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
const needs_full_update = connection ?
|
|
|
|
await this.saveTransaction(connection) :
|
2020-09-25 23:42:15 +02:00
|
|
|
await MysqlConnectionManager.wrapTransaction(async connection => await this.saveTransaction(connection));
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
const callback = async () => {
|
|
|
|
if (needs_full_update) {
|
2020-09-25 23:42:15 +02:00
|
|
|
const query = this._factory.select();
|
|
|
|
for (const field of this._factory.getPrimaryKeyFields()) {
|
|
|
|
query.where(field, this[field]);
|
|
|
|
}
|
|
|
|
query.limit(1);
|
|
|
|
const result = await query.execute(connection);
|
2020-09-06 10:43:45 +02:00
|
|
|
this.updateWithData(result.results[0]);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
await this.afterSave?.();
|
2020-04-22 15:52:17 +02:00
|
|
|
};
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
if (postHook) {
|
|
|
|
postHook(callback);
|
2020-04-22 15:52:17 +02:00
|
|
|
} else {
|
|
|
|
await callback();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
private async saveTransaction(connection: Connection): Promise<boolean> {
|
2020-04-22 15:52:17 +02:00
|
|
|
// Before save
|
2020-09-25 22:03:22 +02:00
|
|
|
await this.beforeSave?.(connection);
|
2020-09-25 23:42:15 +02:00
|
|
|
if (!this.exists() && this.hasProperty('created_at')) {
|
2020-08-28 14:16:25 +02:00
|
|
|
this.created_at = new Date();
|
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
if (this.exists() && this.hasProperty('updated_at')) {
|
2020-04-22 15:52:17 +02:00
|
|
|
this.updated_at = new Date();
|
|
|
|
}
|
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
const properties = [];
|
2020-09-25 23:42:15 +02:00
|
|
|
const values: QueryVariable[] = [];
|
2020-09-06 10:43:45 +02:00
|
|
|
let needsFullUpdate = false;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
if (this.exists()) {
|
2020-09-25 23:42:15 +02:00
|
|
|
const data: { [K in keyof this]?: this[K] } = {};
|
2020-07-24 12:13:28 +02:00
|
|
|
for (const property of this._properties) {
|
|
|
|
const value = this[property];
|
2020-09-06 10:43:45 +02:00
|
|
|
|
|
|
|
if (value === undefined) needsFullUpdate = true;
|
|
|
|
else data[property] = value;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
2020-09-06 10:43:45 +02:00
|
|
|
|
|
|
|
const query = this._factory.update(data);
|
2020-07-24 15:40:10 +02:00
|
|
|
for (const indexField of this._factory.getPrimaryKeyFields()) {
|
2020-09-06 10:43:45 +02:00
|
|
|
query.where(indexField, this[indexField]);
|
2020-06-04 14:59:23 +02:00
|
|
|
}
|
|
|
|
await query.execute(connection);
|
2020-04-22 15:52:17 +02:00
|
|
|
} else {
|
|
|
|
const props_holders = [];
|
2020-07-24 12:13:28 +02:00
|
|
|
for (const property of this._properties) {
|
2020-09-25 23:42:15 +02:00
|
|
|
let value: ModelFieldData = this[property];
|
2020-09-06 10:43:45 +02:00
|
|
|
|
|
|
|
if (value === undefined) {
|
|
|
|
needsFullUpdate = true;
|
|
|
|
} else {
|
2020-09-25 23:42:15 +02:00
|
|
|
if (!isQueryVariable(value)) {
|
|
|
|
value = value.toString();
|
|
|
|
}
|
2020-07-24 12:13:28 +02:00
|
|
|
properties.push(property);
|
2020-04-22 15:52:17 +02:00
|
|
|
props_holders.push('?');
|
2020-09-25 23:42:15 +02:00
|
|
|
values.push(value as QueryVariable);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
}
|
2020-09-06 10:43:45 +02:00
|
|
|
|
2020-09-04 15:07:31 +02:00
|
|
|
const fieldNames = properties.map(f => `\`${f}\``).join(', ');
|
|
|
|
const result = await query(`INSERT INTO ${this.table} (${fieldNames}) VALUES(${props_holders.join(', ')})`, values, connection);
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
if (this.hasProperty('id')) this.id = Number(result.other?.insertId);
|
2020-09-06 10:43:45 +02:00
|
|
|
this._exists = true;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
return needsFullUpdate;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public async delete(): Promise<void> {
|
2020-09-25 23:42:15 +02:00
|
|
|
if (!await this.exists()) throw new Error('This model instance doesn\'t exist in DB.');
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
const query = this._factory.delete();
|
2020-07-24 15:40:10 +02:00
|
|
|
for (const indexField of this._factory.getPrimaryKeyFields()) {
|
2020-09-06 10:43:45 +02:00
|
|
|
query.where(indexField, this[indexField]);
|
2020-06-04 14:59:23 +02:00
|
|
|
}
|
|
|
|
await query.execute();
|
2020-09-06 10:43:45 +02:00
|
|
|
this._exists = false;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-02 14:07:40 +02:00
|
|
|
public async validate(onlyFormat: boolean = false, connection?: Connection): Promise<void[]> {
|
|
|
|
return await Promise.all(this._properties.map(
|
2020-09-25 23:42:15 +02:00
|
|
|
prop => this._validators[prop]?.execute(prop, this[prop], onlyFormat, connection),
|
2020-09-02 14:07:40 +02:00
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2020-09-06 10:43:45 +02:00
|
|
|
public exists(): boolean {
|
|
|
|
return this._exists;
|
2020-08-05 10:45:13 +02:00
|
|
|
}
|
|
|
|
|
2020-09-02 14:07:40 +02:00
|
|
|
public equals(model: this): boolean {
|
|
|
|
for (const field of this._factory.getPrimaryKeyFields()) {
|
|
|
|
if (this[field] !== model[field]) return false;
|
|
|
|
}
|
|
|
|
return true;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
public get table(): string {
|
|
|
|
return this._factory.table;
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
private get _properties(): (keyof this & string)[] {
|
2020-07-24 12:13:28 +02:00
|
|
|
return Object.getOwnPropertyNames(this).filter(p => {
|
2020-07-26 11:37:01 +02:00
|
|
|
return !p.startsWith('_') &&
|
|
|
|
typeof this[p] !== 'function' &&
|
|
|
|
!(this[p] instanceof ModelRelation);
|
2020-07-24 12:13:28 +02:00
|
|
|
});
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
|
|
|
|
private hasProperty(key: string | number | symbol): key is keyof this {
|
|
|
|
return typeof key === 'string' && this._properties.indexOf(key) >= 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
public getOrFail<K extends keyof this & string>(k: K): NonNullable<this[K]> {
|
|
|
|
if (!this[k]) throw new Error(k + ' not initialized.');
|
|
|
|
return this[k] as NonNullable<this[K]>;
|
|
|
|
}
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
2020-09-06 10:23:32 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
export interface ModelType<M extends Model> extends Type<M> {
|
2020-09-06 10:23:32 +02:00
|
|
|
table: string;
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
new(factory: ModelFactory<never>, isNew: boolean): M;
|
|
|
|
|
|
|
|
getPrimaryKeyFields(): (keyof M & string)[];
|
2020-09-06 10:43:45 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
select<M extends Model>(this: ModelType<M>, ...fields: SelectFields): ModelQuery<M>;
|
2020-09-06 10:23:32 +02:00
|
|
|
}
|