import { Column, BaseEntity, ObjectType, ObjectID, FindOneOptions, FindConditions, Repository, Connection, PrimaryGeneratedColumn } from "typeorm"; import { BadRequest } from "ts-httpexceptions"; import { getCurrentTimeInt } from "../../util/helper" export default class CoreEntity extends BaseEntity { public static connection: Connection; constructor() { super() } // PROPERTIES @PrimaryGeneratedColumn() id: number; @Column() dateCreated: number; @Column() dateUpdated: number; // METHODS static getRepository(this: ObjectType): Repository { const connection: Connection = (this as any).usedConnection || (this as any).connection; return connection.getRepository(this); } save(): Promise { if (!this.hasId()) { this.dateCreated = getCurrentTimeInt() } this.dateUpdated = getCurrentTimeInt() return super.save() } static async findOneOrThrowId( this: ObjectType, id?: string | number | Date | ObjectID, options?: FindOneOptions, replaceName?: string ): Promise { try { return await super.findOneOrFail(id, options) } catch (error) { console.log(error); throw new BadRequest(`${replaceName ? replaceName : this.name} không tồn tại.`) } } static async findOneOrThrowOption( this: ObjectType, options?: FindOneOptions, replaceName?: string ): Promise { try { return await super.findOneOrFail(options) } catch (error) { console.log(error); throw new BadRequest(`${replaceName ? replaceName : this.name} không tồn tại.`) } } } // END FILE