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