swaf/src/db/Model.ts

242 lines
8.1 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import MysqlConnectionManager, {query} from "./MysqlConnectionManager";
import Validator from "./Validator";
import {Connection} from "mysql";
2020-07-24 12:13:28 +02:00
import ModelComponent from "./ModelComponent";
import {Type} from "../Utils";
import ModelFactory from "./ModelFactory";
import ModelRelation from "./ModelRelation";
import ModelQuery, {ModelQueryResult, SelectFields} from "./ModelQuery";
2020-04-22 15:52:17 +02:00
import {Request} from "express";
import Extendable from "../Extendable";
2020-04-22 15:52:17 +02:00
export default abstract class Model implements Extendable<ModelComponent<Model>> {
public static get table(): string {
return this.name
.replace(/(?:^|\.?)([A-Z])/g, (x, y) => '_' + y.toLowerCase())
.replace(/^_/, '')
+ 's';
}
public static getPrimaryKeyFields(): string[] {
return ['id'];
}
public static create<T extends Model>(this: ModelType<T>, data: any): T {
return ModelFactory.get(this).create(data, true);
}
public static select<T extends Model>(this: ModelType<T>, ...fields: SelectFields): ModelQuery<T> {
2020-07-24 12:13:28 +02:00
return ModelFactory.get(this).select(...fields);
2020-04-22 15:52:17 +02:00
}
public static update<T extends Model>(this: ModelType<T>, data: { [key: string]: any }): ModelQuery<T> {
2020-07-24 12:13:28 +02:00
return ModelFactory.get(this).update(data);
2020-04-22 15:52:17 +02:00
}
public static delete<T extends Model>(this: ModelType<T>): ModelQuery<T> {
2020-07-24 12:13:28 +02:00
return ModelFactory.get(this).delete();
2020-04-22 15:52:17 +02:00
}
public static async getById<T extends Model>(this: ModelType<T>, ...id: any): Promise<T | null> {
2020-07-27 10:54:08 +02:00
return ModelFactory.get(this).getById(...id);
}
public static async paginate<T extends Model>(this: ModelType<T>, request: Request, perPage: number = 20, query?: ModelQuery<T>): Promise<ModelQueryResult<T>> {
2020-07-24 12:13:28 +02:00
return ModelFactory.get(this).paginate(request, perPage, query);
2020-04-22 15:52:17 +02:00
}
protected readonly _factory: ModelFactory<Model>;
private readonly _components: ModelComponent<this>[] = [];
private readonly _validators: { [key: string]: Validator<any> | undefined } = {};
private _exists: boolean;
2020-04-22 15:52:17 +02:00
[key: string]: any;
public constructor(factory: ModelFactory<Model>, isNew: boolean) {
if (!factory || !(factory instanceof ModelFactory)) throw new Error('Cannot instantiate model directly.');
this._factory = factory;
this.init();
this._exists = !isNew;
}
2020-07-24 12:13:28 +02:00
protected abstract init(): void;
protected setValidation<T>(propertyName: keyof this): Validator<T> {
const validator = new Validator<T>();
this._validators[propertyName as string] = validator;
return validator;
}
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
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) {
return this as unknown as C;
2020-07-24 12:13:28 +02:00
}
2020-04-22 15:52:17 +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
}
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;
}
public updateWithData(data: any) {
2020-07-24 12:13:28 +02:00
for (const property of this._properties) {
if (data[property] !== undefined) {
this[property] = data[property];
2020-04-22 15:52:17 +02:00
}
}
}
/**
* Override this to automatically fill obvious missing data i.e. from relation or default value that are fetched
* asynchronously.
*/
protected async autoFill?(): Promise<void>;
protected async beforeSave?(connection: Connection): Promise<void>;
2020-04-22 15:52:17 +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> {
if (connection && !postHook) throw new Error('If connection is provided, postHook must be provided too.');
await this.autoFill?.();
2020-04-22 15:52:17 +02:00
await this.validate(false, connection);
const needs_full_update = connection ?
await this.saveTransaction(connection) :
await MysqlConnectionManager.wrapTransaction(async connection => this.saveTransaction(connection));
2020-04-22 15:52:17 +02:00
const callback = async () => {
if (needs_full_update) {
const result = await this._factory.select()
.where('id', this.id!)
.limit(1)
.execute(connection);
this.updateWithData(result.results[0]);
2020-04-22 15:52:17 +02:00
}
await this.afterSave?.();
2020-04-22 15:52:17 +02:00
};
if (connection) {
postHook!(callback);
} else {
await callback();
}
}
private async saveTransaction(connection: Connection): Promise<boolean> {
2020-04-22 15:52:17 +02:00
// Before save
await this.beforeSave?.(connection);
if (!this.exists() && this.hasOwnProperty('created_at')) {
this.created_at = new Date();
}
if (this.exists() && this.hasOwnProperty('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-04-22 15:52:17 +02:00
const values = [];
let needsFullUpdate = false;
2020-04-22 15:52:17 +02:00
if (this.exists()) {
const data: any = {};
2020-07-24 12:13:28 +02:00
for (const property of this._properties) {
const value = this[property];
if (value === undefined) needsFullUpdate = true;
else data[property] = value;
2020-04-22 15:52:17 +02:00
}
const query = this._factory.update(data);
for (const indexField of this._factory.getPrimaryKeyFields()) {
query.where(indexField, this[indexField]);
}
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) {
const value = this[property];
if (value === undefined) {
needsFullUpdate = true;
} else {
2020-07-24 12:13:28 +02:00
properties.push(property);
2020-04-22 15:52:17 +02:00
props_holders.push('?');
2020-07-24 12:13:28 +02:00
values.push(value);
2020-04-22 15:52:17 +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-07-24 12:13:28 +02:00
if (this.hasOwnProperty('id')) this.id = result.other.insertId;
this._exists = true;
2020-04-22 15:52:17 +02:00
}
return needsFullUpdate;
2020-04-22 15:52:17 +02:00
}
public async delete(): Promise<void> {
if (!(await this.exists())) throw new Error('This model instance doesn\'t exist in DB.');
const query = this._factory.delete();
for (const indexField of this._factory.getPrimaryKeyFields()) {
query.where(indexField, this[indexField]);
}
await query.execute();
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(
prop => this._validators[prop]?.execute(prop, this[prop], onlyFormat, connection)
));
}
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-07-24 12:13:28 +02:00
private get _properties(): string[] {
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
}
}
export interface ModelType<T extends Model> extends Type<T> {
table: string;
new(factory: ModelFactory<any>, isNew: boolean): T;
getPrimaryKeyFields(): string[];
}