2023-05-26 17:59:22 +01:00
|
|
|
import { Column, DeepPartial, EntityTarget, PrimaryColumn, ObjectLiteral, FindOptionsWhere } from "typeorm";
|
2022-04-24 14:46:37 +01:00
|
|
|
import { v4 } from "uuid";
|
2023-05-26 17:59:22 +01:00
|
|
|
import AppDataSource from "../database/dataSources/appDataSource";
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
export default class BaseEntity {
|
|
|
|
constructor() {
|
|
|
|
this.Id = v4();
|
2023-05-08 18:24:09 +01:00
|
|
|
|
2022-04-24 14:46:37 +01:00
|
|
|
this.WhenCreated = new Date();
|
|
|
|
this.WhenUpdated = new Date();
|
|
|
|
}
|
|
|
|
|
|
|
|
@PrimaryColumn()
|
|
|
|
Id: string;
|
|
|
|
|
|
|
|
@Column()
|
|
|
|
WhenCreated: Date;
|
|
|
|
|
|
|
|
@Column()
|
|
|
|
WhenUpdated: Date;
|
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
public async Save<T extends BaseEntity>(target: EntityTarget<T>, entity: DeepPartial<T>): Promise<void> {
|
2022-04-24 14:46:37 +01:00
|
|
|
this.WhenUpdated = new Date();
|
|
|
|
|
2023-05-26 17:59:22 +01:00
|
|
|
const repository = AppDataSource.getRepository<T>(target);
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
await repository.save(entity);
|
|
|
|
}
|
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
public static async Remove<T extends BaseEntity>(target: EntityTarget<T>, entity: T): Promise<void> {
|
2023-05-26 17:59:22 +01:00
|
|
|
const repository = AppDataSource.getRepository<T>(target);
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
await repository.remove(entity);
|
|
|
|
}
|
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
public static async FetchAll<T extends BaseEntity>(target: EntityTarget<T>, relations?: string[]): Promise<T[]> {
|
2023-05-26 17:59:22 +01:00
|
|
|
const repository = AppDataSource.getRepository<T>(target);
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
const all = await repository.find({ relations: relations || [] });
|
|
|
|
|
|
|
|
return all;
|
|
|
|
}
|
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
public static async FetchOneById<T extends BaseEntity>(target: EntityTarget<T>, id: string, relations?: string[]): Promise<T | null> {
|
2023-05-26 17:59:22 +01:00
|
|
|
const repository = AppDataSource.getRepository<T>(target);
|
2022-04-24 14:46:37 +01:00
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
const single = await repository.findOne({ where: ({ Id: id } as FindOptionsWhere<T>), relations: relations || {} });
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
return single;
|
|
|
|
}
|
|
|
|
|
2023-05-08 18:24:09 +01:00
|
|
|
public static async Any<T extends ObjectLiteral>(target: EntityTarget<T>): Promise<boolean> {
|
2023-05-26 17:59:22 +01:00
|
|
|
const repository = AppDataSource.getRepository<T>(target);
|
2022-04-24 14:46:37 +01:00
|
|
|
|
|
|
|
const any = await repository.find();
|
|
|
|
|
|
|
|
return any.length > 0;
|
|
|
|
}
|
|
|
|
}
|