Make models extendable

This commit is contained in:
Alice Gaudon 2020-07-24 12:13:28 +02:00
parent f03d74412c
commit 7f398c1d4e
18 changed files with 377 additions and 282 deletions

View File

@ -1,5 +1,8 @@
import Migration from "../../db/Migration";
import {Connection} from "mysql";
import ModelFactory from "../../db/ModelFactory";
import User from "../models/User";
import UserApprovedComponent from "../models/UserApprovedComponent";
export default class AddApprovedFieldToUsersTable extends Migration {
public async install(connection: Connection): Promise<void> {
@ -9,4 +12,8 @@ export default class AddApprovedFieldToUsersTable extends Migration {
public async rollback(connection: Connection): Promise<void> {
await this.query('ALTER TABLE users DROP COLUMN approved', connection);
}
public registerModels(): void {
ModelFactory.get(User).addComponent(UserApprovedComponent);
}
}

View File

@ -1,23 +1,30 @@
import Migration from "../../db/Migration";
import {Connection} from "mysql";
import ModelFactory from "../../db/ModelFactory";
import MagicLink from "../models/MagicLink";
export default class CreateMagicLinksTable extends Migration {
async install(connection: Connection): Promise<void> {
await this.query('CREATE TABLE magic_links(' +
'id INT NOT NULL AUTO_INCREMENT,' +
'session_id CHAR(32) UNIQUE NOT NULL,' +
'email VARCHAR(254) NOT NULL,' +
'token CHAR(96) NOT NULL,' +
'action_type VARCHAR(64) NOT NULL,' +
'original_url VARCHAR(1745) NOT NULL,' +
'generated_at DATETIME NOT NULL,' +
'authorized BOOLEAN NOT NULL,' +
'PRIMARY KEY(id)' +
')', connection);
public async install(connection: Connection): Promise<void> {
await this.query(`CREATE TABLE magic_links
(
id INT NOT NULL AUTO_INCREMENT,
session_id CHAR(32) UNIQUE NOT NULL,
email VARCHAR(254) NOT NULL,
token CHAR(96) NOT NULL,
action_type VARCHAR(64) NOT NULL,
original_url VARCHAR(1745) NOT NULL,
generated_at DATETIME NOT NULL,
authorized BOOLEAN NOT NULL,
PRIMARY KEY (id)
)`, connection);
}
async rollback(connection: Connection): Promise<void> {
public async rollback(connection: Connection): Promise<void> {
await this.query('DROP TABLE magic_links', connection);
}
public registerModels(): void {
ModelFactory.register(MagicLink);
}
}

View File

@ -1,29 +1,39 @@
import Migration from "../../db/Migration";
import {Connection} from "mysql";
import ModelFactory from "../../db/ModelFactory";
import User from "../models/User";
import UserEmail from "../models/UserEmail";
export default class CreateUsersAndUserEmailsTable extends Migration {
async install(connection: Connection): Promise<void> {
await this.query('CREATE TABLE users(' +
'id INT NOT NULL AUTO_INCREMENT,' +
'name VARCHAR(64),' +
'is_admin BOOLEAN NOT NULL DEFAULT false,' +
'created_at DATETIME NOT NULL DEFAULT NOW(),' +
'updated_at DATETIME NOT NULL DEFAULT NOW(),' +
'PRIMARY KEY(id)' +
')', connection);
await this.query('CREATE TABLE user_emails(' +
'id INT NOT NULL AUTO_INCREMENT,' +
'user_id INT,' +
'email VARCHAR(254) UNIQUE NOT NULL,' +
'main BOOLEAN NOT NULL,' +
'created_at DATETIME NOT NULL DEFAULT NOW(),' +
'PRIMARY KEY(id),' +
'FOREIGN KEY user_fk (user_id) REFERENCES users (id) ON DELETE CASCADE' +
')', connection);
public async install(connection: Connection): Promise<void> {
await this.query(`CREATE TABLE users
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(64),
is_admin BOOLEAN NOT NULL DEFAULT false,
created_at DATETIME NOT NULL DEFAULT NOW(),
updated_at DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
)`, connection);
await this.query(`CREATE TABLE user_emails
(
id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
email VARCHAR(254) UNIQUE NOT NULL,
main BOOLEAN NOT NULL,
created_at DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY (id),
FOREIGN KEY user_fk (user_id) REFERENCES users (id) ON DELETE CASCADE
)`, connection);
}
async rollback(connection: Connection): Promise<void> {
public async rollback(connection: Connection): Promise<void> {
await this.query('DROP TABLE user_emails', connection);
await this.query('DROP TABLE users', connection);
}
public registerModels(): void {
ModelFactory.register(User);
ModelFactory.register(UserEmail);
}
}

View File

@ -2,7 +2,6 @@ import crypto from "crypto";
import config from "config";
import Model, {EMAIL_REGEX} from "../../db/Model";
import AuthProof from "../AuthProof";
import Validator from "../../db/Validator";
import User from "./User";
import argon2 from "argon2";
import {WhereTest} from "../../db/ModelQuery";
@ -43,13 +42,12 @@ export default class MagicLink extends Model implements AuthProof {
}
protected init(): void {
this.addProperty<string>('session_id', new Validator().defined().length(32).unique(this));
this.addProperty<string>('email', new Validator().defined().regexp(EMAIL_REGEX));
this.addProperty<string>('token', new Validator().defined().length(96));
this.addProperty<string>('action_type', new Validator().defined().maxLength(64));
this.addProperty<string>('original_url', new Validator().defined().maxLength(1745));
this.addProperty<Date>('generated_at', new Validator());
this.addProperty<boolean>('authorized', new Validator().defined());
this.setValidation('session_id').defined().length(32).unique(this);
this.setValidation('email').defined().regexp(EMAIL_REGEX);
this.setValidation('token').defined().length(96);
this.setValidation('action_type').defined().maxLength(64);
this.setValidation('original_url').defined().maxLength(1745);
this.setValidation('authorized').defined();
}
public async isOwnedBy(userId: number): Promise<boolean> {

View File

@ -1,10 +1,11 @@
import Model from "../../db/Model";
import Validator from "../../db/Validator";
import MysqlConnectionManager from "../../db/MysqlConnectionManager";
import AddApprovedFieldToUsersTable from "../migrations/AddApprovedFieldToUsersTable";
import config from "config";
import {ManyModelRelation} from "../../db/ModelRelation";
import UserEmail from "./UserEmail";
import ModelFactory from "../../db/ModelFactory";
import UserApprovedComponent from "./UserApprovedComponent";
export default class User extends Model {
public static isApprovalMode(): boolean {
@ -12,34 +13,32 @@ export default class User extends Model {
}
public name?: string;
public approved!: boolean;
public is_admin!: boolean;
public created_at?: Date;
public updated_at?: Date;
public readonly emails = new ManyModelRelation<this, UserEmail>(this, UserEmail, {
public readonly emails = new ManyModelRelation(this, ModelFactory.get(UserEmail), {
localKey: 'id',
foreignKey: 'user_id'
});
public readonly mainEmail = this.emails.cloneReduceToOne().constraint(q => q.where('main', true));
constructor(data: any) {
public constructor(data: any) {
super(data);
if (this.approved === undefined) this.approved = false;
if (this.is_admin === undefined) this.is_admin = false;
}
protected init(): void {
this.addProperty<string>('name', new Validator().acceptUndefined().between(3, 64));
if (User.isApprovalMode()) this.addProperty<boolean>('approved', new Validator().defined());
this.addProperty<boolean>('is_admin', new Validator().defined());
this.addProperty<Date>('created_at');
this.addProperty<Date>('updated_at');
this.setValidation('name').acceptUndefined().between(3, 64);
if (User.isApprovalMode()) {
this.setValidation('approved').defined();
}
this.setValidation('is_admin').defined();
}
public isApproved(): boolean {
return !User.isApprovalMode() || this.approved!;
return !User.isApprovalMode() || this.as(UserApprovedComponent).approved;
}
}

View File

@ -0,0 +1,6 @@
import ModelComponent from "../../db/ModelComponent";
import User from "./User";
export default class UserApprovedComponent extends ModelComponent<User> {
public approved!: boolean;
}

View File

@ -1,9 +1,9 @@
import User from "./User";
import {Connection} from "mysql";
import Model, {EMAIL_REGEX} from "../../db/Model";
import Validator from "../../db/Validator";
import {query} from "../../db/MysqlConnectionManager";
import {OneModelRelation} from "../../db/ModelRelation";
import ModelFactory from "../../db/ModelFactory";
export default class UserEmail extends Model {
public user_id?: number;
@ -11,28 +11,27 @@ export default class UserEmail extends Model {
private main!: boolean;
public created_at?: Date;
public readonly user = new OneModelRelation<this, User>(this, User, {
public readonly user = new OneModelRelation<UserEmail, User>(this, ModelFactory.get(User), {
localKey: 'user_id',
foreignKey: 'id'
});
private wasSetToMain: boolean = false;
private _wasSetToMain: boolean = false;
constructor(data: any) {
super(data);
}
protected init(): void {
this.addProperty<number>('user_id', new Validator().acceptUndefined().exists(User, 'id'));
this.addProperty<string>('email', new Validator().defined().regexp(EMAIL_REGEX).unique(this));
this.addProperty<boolean>('main', new Validator().defined());
this.addProperty<Date>('created_at', new Validator());
this.setValidation('user_id').acceptUndefined().exists(User, 'id');
this.setValidation('email').defined().regexp(EMAIL_REGEX).unique(this);
this.setValidation('main').defined();
}
async beforeSave(exists: boolean, connection: Connection) {
if (this.wasSetToMain) {
protected async beforeSave(exists: boolean, connection: Connection) {
if (this._wasSetToMain) {
await query(`UPDATE ${this.table} SET main=false WHERE user_id=${this.user_id}`, null, connection);
this.wasSetToMain = false;
this._wasSetToMain = false;
}
}
@ -43,7 +42,7 @@ export default class UserEmail extends Model {
public setMain() {
if (!this.isMain()) {
this.main = true;
this.wasSetToMain = true;
this._wasSetToMain = true;
}
}
}

View File

@ -4,17 +4,19 @@ import MysqlConnectionManager from "./MysqlConnectionManager";
export default abstract class Migration {
public readonly version: number;
constructor(version: number) {
public constructor(version: number) {
this.version = version;
}
async shouldRun(currentVersion: number): Promise<boolean> {
public async shouldRun(currentVersion: number): Promise<boolean> {
return this.version > currentVersion;
}
abstract async install(connection: Connection): Promise<void>;
public abstract async install(connection: Connection): Promise<void>;
abstract async rollback(connection: Connection): Promise<void>;
public abstract async rollback(connection: Connection): Promise<void>;
public abstract registerModels(): void;
protected async query(queryString: string, connection: Connection): Promise<void> {
await MysqlConnectionManager.query(queryString, undefined, connection);

View File

@ -1,138 +1,75 @@
import MysqlConnectionManager, {query} from "./MysqlConnectionManager";
import Validator from "./Validator";
import {Connection} from "mysql";
import ModelComponent from "./ModelComponent";
import {Type} from "../Utils";
import ModelFactory from "./ModelFactory";
import ModelRelation from "./ModelRelation";
import ModelQuery, {ModelQueryResult} from "./ModelQuery";
import {Request} from "express";
import {Type} from "../Utils";
export interface ModelClass<M extends Model> extends Type<M> {
getFactory<M extends Model>(factory?: ModelFactory<M>): ModelFactory<M>;
table: string;
getPrimaryKey(modelData: any): string;
getPrimaryKeyFields(): string[];
select<M extends Model>(...fields: string[]): ModelQuery<M>;
update<M extends Model>(data: { [key: string]: any }): ModelQuery<M>;
delete<M extends Model>(): ModelQuery<M>;
}
export default abstract class Model {
public static get table(): string {
return this.name
.replace(/(?:^|\.?)([A-Z])/g, (x, y) => '_' + y.toLowerCase())
.replace(/^_/, '')
+ 's';
public static select<T extends Model>(this: Type<T>, ...fields: string[]): ModelQuery<T> {
return ModelFactory.get(this).select(...fields);
}
public static async getById<T extends Model>(this: ModelClass<T>, id: number): Promise<T | null> {
return this.select<T>().where('id', id).first();
public static update<T extends Model>(this: Type<T>, data: { [key: string]: any }): ModelQuery<T> {
return ModelFactory.get(this).update(data);
}
public static async paginate<T extends Model>(this: ModelClass<T>, request: Request, perPage: number = 20, query?: ModelQuery<T>): Promise<ModelQueryResult<T>> {
let page = request.params.page ? parseInt(request.params.page) : 1;
if (!query) query = this.select();
if (request.params.sortBy) {
const dir = request.params.sortDirection;
query = query.sortBy(request.params.sortBy, dir === 'ASC' || dir === 'DESC' ? dir : undefined);
} else {
query = query.sortBy('id');
}
return await query.paginate(page, perPage);
public static delete<T extends Model>(this: Type<T>): ModelQuery<T> {
return ModelFactory.get(this).delete();
}
public static select<T extends Model>(this: ModelClass<T>, ...fields: string[]): ModelQuery<T> {
return ModelQuery.select(this, ...fields);
public static async getById<T extends Model>(this: Type<T>, ...id: any): Promise<T | null> {
return ModelFactory.get(this).getById(id);
}
public static update<T extends Model>(this: ModelClass<T>, data: { [key: string]: any }): ModelQuery<T> {
return ModelQuery.update(this, data);
public static async paginate<T extends Model>(this: Type<T>, request: Request, perPage: number = 20, query?: ModelQuery<T>): Promise<ModelQueryResult<T>> {
return ModelFactory.get(this).paginate(request, perPage, query);
}
public static delete<T extends Model>(this: ModelClass<T>): ModelQuery<T> {
return ModelQuery.delete(this);
}
public static getPrimaryKey(modelData: any): string {
return this.getPrimaryKeyFields().map(f => `${modelData[f]}`).join(',');
}
public static getPrimaryKeyFields(): string[] {
return ['id'];
}
public static async loadRelation<T extends Model>(models: T[], relation: string, model: Function, localField: string) {
const loadMap: { [p: number]: (model: T) => void } = {};
const ids = models.map(m => {
m.relations[relation] = null;
if (m[localField]) loadMap[m[localField]] = v => m.relations[relation] = v;
return m[localField];
}).filter(id => id);
for (const v of await (<any>model).models((<any>model).select().whereIn('id', ids))) {
loadMap[v.id!](v);
}
}
public static getFactory<T extends Model>(this: ModelClass<T>, factory?: ModelFactory<T>): ModelFactory<T> {
if (factory === undefined) {
factory = (<any>this).FACTORY;
if (factory === undefined) factory = data => new (<any>this)(data);
}
return factory;
}
protected readonly modelClass: ModelClass<this> = <ModelClass<this>>this.constructor;
protected readonly properties: ModelProperty<any>[] = [];
public id?: number;
private readonly automaticIdProperty: boolean;
protected readonly _factory!: ModelFactory<any>;
private readonly _components: ModelComponent<any>[] = [];
private readonly _validators: { [key: string]: Validator<any> } = {};
[key: string]: any;
public constructor(data: any, automaticIdProperty: boolean = true) {
this.automaticIdProperty = automaticIdProperty;
if (automaticIdProperty) {
this.addProperty<number>('id', new Validator());
}
public constructor(data: any) {
this.init();
this.updateWithData(data);
}
public getPrimaryKey(): string {
return this.modelClass.getPrimaryKey(this);
}
public getPrimaryKeyFields(): string[] {
return this.modelClass.getPrimaryKeyFields();
public setFactory(factory: ModelFactory<any>) {
(this as any)._factory = factory;
}
protected abstract init(): void;
protected addProperty<T>(name: string, validator?: Validator<T> | RegExp) {
if (validator === undefined) validator = new Validator();
if (validator instanceof RegExp) {
const regexp = validator;
validator = new Validator().regexp(regexp);
protected setValidation<T>(propertyName: keyof this): Validator<T> {
const validator = new Validator<T>();
this._validators[propertyName as string] = validator;
return validator;
}
const prop = new ModelProperty<T>(name, validator);
this.properties.push(prop);
Object.defineProperty(this, name, {
get: () => prop.value,
set: (value: T) => prop.value = value,
});
public addComponent(modelComponent: ModelComponent<this>): void {
modelComponent.init();
this._components.push(modelComponent);
}
public as<T extends ModelComponent<any>>(type: Type<T>): T {
for (const component of this._components) {
if (component instanceof type) {
return <any>this;
}
}
throw new Error(`Component ${type.name} was not initialized for this ${this.constructor.name}.`);
}
private updateWithData(data: any) {
if (this.automaticIdProperty) this.id = data['id'];
for (const prop of this.properties) {
if (data[prop.name] !== undefined) {
this[prop.name] = data[prop.name];
for (const property of this._properties) {
if (data[property] !== undefined) {
this[property] = data[property];
}
}
}
@ -157,7 +94,7 @@ export default abstract class Model {
const callback = async () => {
if (needs_full_update) {
this.updateWithData((await this.modelClass.select().where('id', this.id!).limit(1).execute()).results[0]);
this.updateWithData((await this._factory.select().where('id', this.id!).limit(1).execute()).results[0]);
}
await this.afterSave();
@ -177,50 +114,46 @@ export default abstract class Model {
this.updated_at = new Date();
}
const props = [];
const properties = [];
const values = [];
if (exists) {
const data: any = {};
for (const prop of this.properties) {
if (prop.value !== undefined) {
data[prop.name] = prop.value;
for (const property of this._properties) {
const value = this[property];
if (value !== undefined) {
data[property] = value;
} else {
needs_full_update = true;
}
}
let query = this.modelClass.update(data);
let query = this._factory.update(data);
for (const indexField of this.getPrimaryKeyFields()) {
query = query.where(indexField, this[indexField]);
}
await query.execute(connection);
} else {
const props_holders = [];
for (const prop of this.properties) {
if (prop.value !== undefined) {
props.push(prop.name);
for (const property of this._properties) {
const value = this[property];
if (value !== undefined) {
properties.push(property);
props_holders.push('?');
values.push(prop.value);
values.push(value);
} else {
needs_full_update = true;
}
}
const result = await query(`INSERT INTO ${this.table} (${props.join(', ')}) VALUES(${props_holders.join(', ')})`, values, connection);
const result = await query(`INSERT INTO ${this.table} (${properties.join(', ')}) VALUES(${props_holders.join(', ')})`, values, connection);
if (this.automaticIdProperty) this.id = result.other.insertId;
if (this.hasOwnProperty('id')) this.id = result.other.insertId;
}
return needs_full_update;
}
public get table(): string {
return this.modelClass.table;
}
public async exists(): Promise<boolean> {
if (!this.id) return false;
let query = this.modelClass.select('1');
let query = this._factory.select('1');
for (const indexField of this.getPrimaryKeyFields()) {
query = query.where(indexField, this[indexField]);
}
@ -230,43 +163,27 @@ export default abstract class Model {
public async delete(): Promise<void> {
if (!(await this.exists())) throw new Error('This model instance doesn\'t exist in DB.');
let query = this.modelClass.delete();
let query = this._factory.delete();
for (const indexField of this.getPrimaryKeyFields()) {
query = query.where(indexField, this[indexField]);
}
await query.execute();
if (this.automaticIdProperty) this.id = undefined;
}
public async validate(onlyFormat: boolean = false, connection?: Connection): Promise<void[]> {
return await Promise.all(this.properties.map(prop => prop.validate(onlyFormat, connection)));
}
return await Promise.all(this._properties.map(
prop => this._validators[prop]?.execute(prop, this[prop], onlyFormat, connection)
));
}
export interface ModelFactory<T extends Model> {
(data: any): T;
public get table(): string {
return this._factory.table;
}
class ModelProperty<T> {
public readonly name: string;
private readonly validator: Validator<T>;
private val?: T;
constructor(name: string, validator: Validator<T>) {
this.name = name;
this.validator = validator;
}
public async validate(onlyFormat: boolean, connection?: Connection): Promise<void> {
return await this.validator.execute(this.name, this.value, onlyFormat, connection);
}
public get value(): T | undefined {
return this.val;
}
public set value(val: T | undefined) {
this.val = val;
private get _properties(): string[] {
return Object.getOwnPropertyNames(this).filter(p => {
return !p.startsWith('_') && !(this[p] instanceof ModelRelation);
});
}
}

31
src/db/ModelComponent.ts Normal file
View File

@ -0,0 +1,31 @@
import Model from "./Model";
import Validator from "./Validator";
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;
}
public init(): void {
for (const property of this._properties) {
if (!property.startsWith('_')) {
(this._model as Model)[property] = this[property];
}
}
}
protected setValidation<T>(propertyName: keyof this): Validator<T> {
const validator = new Validator<T>();
this._validators[propertyName as string] = validator;
return validator;
}
private get _properties(): string[] {
return Object.getOwnPropertyNames(this).filter(p => !p.startsWith('_'));
}
}

107
src/db/ModelFactory.ts Normal file
View File

@ -0,0 +1,107 @@
import ModelComponent from "./ModelComponent";
import Model from "./Model";
import ModelQuery, {ModelQueryResult} from "./ModelQuery";
import {Request} from "express";
import {Type} from "../Utils";
export default class ModelFactory<T extends Model> {
private static readonly factories: { [modelType: string]: ModelFactory<any> } = {};
public static register<M extends Model>(modelType: Type<M>) {
if (this.factories[modelType.name]) throw new Error(`Factory for type ${modelType.name} already defined.`);
this.factories[modelType.name] = new ModelFactory<M>(modelType);
}
public static get<M extends Model>(modelType: Type<M>): ModelFactory<M> {
const factory = this.factories[modelType.name];
if (!factory) throw new Error(`No factory registered for ${modelType.name}.`);
return factory;
}
private readonly modelType: Type<T>;
private readonly components: ModelComponentFactory<T>[] = [];
protected constructor(modelType: Type<T>) {
this.modelType = modelType;
}
public addComponent(modelComponentFactory: ModelComponentFactory<T>) {
this.components.push(modelComponentFactory);
}
public make(data: any): T {
const model = new this.modelType(data);
for (const component of this.components) {
model.addComponent(new component(model));
}
model.setFactory(this);
return model;
}
public get table(): string {
return this.constructor.name
.replace(/(?:^|\.?)([A-Z])/g, (x, y) => '_' + y.toLowerCase())
.replace(/^_/, '')
+ 's';
}
public select(...fields: string[]): ModelQuery<T> {
return ModelQuery.select(this, ...fields);
}
public update(data: { [key: string]: any }): ModelQuery<T> {
return ModelQuery.update(this, data);
}
public delete(): ModelQuery<T> {
return ModelQuery.delete(this);
}
public getPrimaryKeyFields(): string[] {
return ['id'];
}
public getPrimaryKey(modelData: any): any[] {
return this.getPrimaryKeyFields().map(f => modelData[f]);
}
public getPrimaryKeyString(modelData: any): string {
return this.getPrimaryKey(modelData).join(',');
}
public async getById(...id: any): Promise<T | null> {
let query = this.select();
const primaryKeyFields = this.getPrimaryKeyFields();
for (let i = 0; i < primaryKeyFields.length; i++) {
query = query.where(primaryKeyFields[i], id[i]);
}
return query.first();
}
public async paginate(request: Request, perPage: number = 20, query?: ModelQuery<T>): Promise<ModelQueryResult<T>> {
let page = request.params.page ? parseInt(request.params.page) : 1;
if (!query) query = this.select();
if (request.params.sortBy) {
const dir = request.params.sortDirection;
query = query.sortBy(request.params.sortBy, dir === 'ASC' || dir === 'DESC' ? dir : undefined);
} else {
query = query.sortBy('id');
}
return await query.paginate(page, perPage);
}
public async loadRelation(models: T[], relation: string, model: Function, localField: string) {
const loadMap: { [p: number]: (model: T) => void } = {};
const ids = models.map(m => {
m.relations[relation] = null;
if (m[localField]) loadMap[m[localField]] = v => m.relations[relation] = v;
return m[localField];
}).filter(id => id);
for (const v of await (<any>model).models((<any>model).select().whereIn('id', ids))) {
loadMap[v.id!](v);
}
}
}
export type ModelComponentFactory<T extends Model> = new (model: T) => ModelComponent<T>;

View File

@ -1,15 +1,16 @@
import {query, QueryResult} from "./MysqlConnectionManager";
import {Connection} from "mysql";
import Model, {ModelClass} from "./Model";
import Model from "./Model";
import Pagination from "../Pagination";
import ModelRelation from "./ModelRelation";
import ModelFactory from "./ModelFactory";
export default class ModelQuery<M extends Model> {
public static select<M extends Model>(modelClass: ModelClass<M>, ...fields: string[]): ModelQuery<M> {
return new ModelQuery(QueryType.SELECT, modelClass, fields.length > 0 ? fields : ['*']);
public static select<M extends Model>(factory: ModelFactory<M>, ...fields: string[]): ModelQuery<M> {
return new ModelQuery(QueryType.SELECT, factory, fields.length > 0 ? fields : ['*']);
}
public static update<M extends Model>(modelClass: ModelClass<M>, data: {
public static update<M extends Model>(factory: ModelFactory<M>, data: {
[key: string]: any
}): ModelQuery<M> {
const fields = [];
@ -18,15 +19,15 @@ export default class ModelQuery<M extends Model> {
fields.push(new UpdateFieldValue(key, data[key], false));
}
}
return new ModelQuery(QueryType.UPDATE, modelClass, fields);
return new ModelQuery(QueryType.UPDATE, factory, fields);
}
public static delete<M extends Model>(modelClass: ModelClass<M>): ModelQuery<M> {
return new ModelQuery(QueryType.DELETE, modelClass);
public static delete<M extends Model>(factory: ModelFactory<M>): ModelQuery<M> {
return new ModelQuery(QueryType.DELETE, factory);
}
private readonly type: QueryType;
private readonly modelClass: ModelClass<M>;
private readonly factory: ModelFactory<M>;
private readonly table: string;
private readonly fields: (string | SelectFieldValue | UpdateFieldValue)[];
private _leftJoin?: string;
@ -39,10 +40,10 @@ export default class ModelQuery<M extends Model> {
private readonly relations: string[] = [];
private _pivot?: string[];
private constructor(type: QueryType, modelClass: ModelClass<M>, fields?: (string | SelectFieldValue | UpdateFieldValue)[]) {
private constructor(type: QueryType, factory: ModelFactory<M>, fields?: (string | SelectFieldValue | UpdateFieldValue)[]) {
this.type = type;
this.modelClass = modelClass;
this.table = modelClass.table;
this.factory = factory;
this.table = factory.table;
this.fields = fields || [];
}
@ -168,9 +169,8 @@ export default class ModelQuery<M extends Model> {
relationMap[relation] = [];
}
const factory = this.modelClass.getFactory<M>();
for (const result of queryResult.results) {
const model = factory(result);
const model = this.factory.make(result);
models.push(model);
if (this._pivot) {

View File

@ -1,16 +1,17 @@
import ModelQuery, {ModelQueryResult, WhereTest} from "./ModelQuery";
import Model, {ModelClass} from "./Model";
import Model from "./Model";
import ModelFactory from "./ModelFactory";
export default abstract class ModelRelation<S extends Model, O extends Model, R extends O | O[] | null> {
protected readonly model: S;
protected readonly foreignModelClass: ModelClass<O>;
protected readonly foreignFactory: ModelFactory<O>;
protected readonly query: ModelQuery<O>;
protected cachedModels?: R;
protected constructor(model: S, foreignModelClass: ModelClass<O>) {
protected constructor(model: S, foreignFactory: ModelFactory<O>) {
this.model = model;
this.foreignModelClass = foreignModelClass;
this.query = this.foreignModelClass.select();
this.foreignFactory = foreignFactory;
this.query = this.foreignFactory.select();
}
public abstract clone(): ModelRelation<S, O, R>;
@ -46,13 +47,13 @@ export type QueryModifier<M extends Model> = (query: ModelQuery<M>) => ModelQuer
export class OneModelRelation<S extends Model, O extends Model> extends ModelRelation<S, O, O | null> {
protected readonly dbProperties: RelationDatabaseProperties;
constructor(model: S, foreignModelClass: ModelClass<O>, dbProperties: RelationDatabaseProperties) {
super(model, foreignModelClass);
constructor(model: S, foreignFactory: ModelFactory<O>, dbProperties: RelationDatabaseProperties) {
super(model, foreignFactory);
this.dbProperties = dbProperties;
}
public clone(): OneModelRelation<S, O> {
return new OneModelRelation(this.model, this.foreignModelClass, this.dbProperties);
return new OneModelRelation(this.model, this.foreignFactory, this.dbProperties);
}
public getModelID() {
@ -82,17 +83,17 @@ export class OneModelRelation<S extends Model, O extends Model> extends ModelRel
export class ManyModelRelation<S extends Model, O extends Model> extends ModelRelation<S, O, O[]> {
protected readonly dbProperties: RelationDatabaseProperties;
constructor(model: S, foreignModelClass: ModelClass<O>, dbProperties: RelationDatabaseProperties) {
super(model, foreignModelClass);
constructor(model: S, foreignFactory: ModelFactory<O>, dbProperties: RelationDatabaseProperties) {
super(model, foreignFactory);
this.dbProperties = dbProperties;
}
public clone(): ManyModelRelation<S, O> {
return new ManyModelRelation<S, O>(this.model, this.foreignModelClass, this.dbProperties);
return new ManyModelRelation<S, O>(this.model, this.foreignFactory, this.dbProperties);
}
public cloneReduceToOne(): OneModelRelation<S, O> {
return new OneModelRelation<S, O>(this.model, this.foreignModelClass, this.dbProperties);
return new OneModelRelation<S, O>(this.model, this.foreignFactory, this.dbProperties);
}
public getModelID(): any {
@ -123,16 +124,16 @@ export class ManyModelRelation<S extends Model, O extends Model> extends ModelRe
export class ManyThroughModelRelation<S extends Model, O extends Model> extends ModelRelation<S, O, O[]> {
protected readonly dbProperties: PivotRelationDatabaseProperties;
constructor(model: S, foreignModelClass: ModelClass<O>, dbProperties: PivotRelationDatabaseProperties) {
super(model, foreignModelClass);
constructor(model: S, foreignFactory: ModelFactory<O>, dbProperties: PivotRelationDatabaseProperties) {
super(model, foreignFactory);
this.dbProperties = dbProperties;
this.query
.leftJoin(`${this.dbProperties.pivotTable} as pivot`)
.on(`pivot.${this.dbProperties.foreignPivotKey}`, `${this.foreignModelClass.table}.${this.dbProperties.foreignKey}`);
.on(`pivot.${this.dbProperties.foreignPivotKey}`, `${this.foreignFactory.table}.${this.dbProperties.foreignKey}`);
}
public clone(): ManyThroughModelRelation<S, O> {
return new ManyThroughModelRelation<S, O>(this.model, this.foreignModelClass, this.dbProperties);
return new ManyThroughModelRelation<S, O>(this.model, this.foreignFactory, this.dbProperties);
}
public getModelID(): any {

View File

@ -192,6 +192,8 @@ export default class MysqlConnectionManager {
]);
});
}
migration.registerModels();
}
}

View File

@ -1,25 +1,32 @@
import Migration from "../db/Migration";
import {Connection} from "mysql";
import ModelFactory from "../db/ModelFactory";
import Log from "../models/Log";
/**
* Must be the first migration
*/
export default class CreateLogsTable extends Migration {
async install(connection: Connection): Promise<void> {
await this.query('CREATE TABLE logs(' +
'id INT NOT NULL AUTO_INCREMENT,' +
'level TINYINT UNSIGNED NOT NULL,' +
'message TEXT NOT NULL,' +
'log_id BINARY(16),' +
'error_name VARCHAR(128),' +
'error_message VARCHAR(512),' +
'error_stack TEXT,' +
'created_at DATETIME NOT NULL DEFAULT NOW(),' +
'PRIMARY KEY (id)' +
')', connection);
public async install(connection: Connection): Promise<void> {
await this.query(`CREATE TABLE logs
(
id INT NOT NULL AUTO_INCREMENT,
level TINYINT UNSIGNED NOT NULL,
message TEXT NOT NULL,
log_id BINARY(16),
error_name VARCHAR(128),
error_message VARCHAR(512),
error_stack TEXT,
created_at DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
)`, connection);
}
async rollback(connection: Connection): Promise<void> {
public async rollback(connection: Connection): Promise<void> {
await this.query('DROP TABLE logs', connection);
}
public registerModels(): void {
ModelFactory.register(Log);
}
}

View File

@ -6,7 +6,7 @@ import {query} from "../db/MysqlConnectionManager";
* Must be the first migration
*/
export default class CreateMigrationsTable extends Migration {
async shouldRun(currentVersion: number): Promise<boolean> {
public async shouldRun(currentVersion: number): Promise<boolean> {
try {
await query('SELECT 1 FROM migrations LIMIT 1');
} catch (e) {
@ -18,16 +18,20 @@ export default class CreateMigrationsTable extends Migration {
return await super.shouldRun(currentVersion);
}
async install(connection: Connection): Promise<void> {
await this.query('CREATE TABLE migrations(' +
'id INT NOT NULL,' +
'name VARCHAR(64) NOT NULL,' +
'migration_date DATE,' +
'PRIMARY KEY (id)' +
')', connection);
public async install(connection: Connection): Promise<void> {
await this.query(`CREATE TABLE migrations
(
id INT NOT NULL,
name VARCHAR(64) NOT NULL,
migration_date DATE,
PRIMARY KEY (id)
)`, connection);
}
async rollback(connection: Connection): Promise<void> {
public async rollback(connection: Connection): Promise<void> {
await this.query('DROP TABLE migrations', connection);
}
public registerModels(): void {
}
}

View File

@ -1,6 +1,5 @@
import Model from "../db/Model";
import {LogLevel, LogLevelKeys} from "../Logger";
import Validator from "../db/Validator";
export default class Log extends Model {
private level?: number;
@ -12,13 +11,12 @@ export default class Log extends Model {
private created_at?: Date;
protected init(): void {
this.addProperty<number>('level', new Validator<number>().defined());
this.addProperty<string>('message', new Validator<string>().defined().between(0, 65535));
this.addProperty<Buffer>('log_id', new Validator<Buffer>().acceptUndefined().length(16));
this.addProperty<string>('error_name', new Validator<string>().acceptUndefined().between(0, 128));
this.addProperty<string>('error_message', new Validator<string>().acceptUndefined().between(0, 512));
this.addProperty<string>('error_stack', new Validator<string>().acceptUndefined().between(0, 65535));
this.addProperty<Date>('created_at', new Validator<Date>());
this.setValidation('level').defined();
this.setValidation('message').defined().between(0, 65535);
this.setValidation('log_id').acceptUndefined().length(16);
this.setValidation('error_name').acceptUndefined().between(0, 128);
this.setValidation('error_message').acceptUndefined().between(0, 512);
this.setValidation('error_stack').acceptUndefined().between(0, 65535);
}
public getLevel(): LogLevelKeys {