52 lines
1.9 KiB
TypeScript
52 lines
1.9 KiB
TypeScript
import { NotFoundException } from "@nestjs/common";
|
|
import { Prisma } from "@prisma/client";
|
|
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/client";
|
|
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";
|
|
|
|
|
|
type UpdatableDelegate<T> = {
|
|
update(args: {
|
|
where: { id: number },
|
|
data: { is_approved: boolean },
|
|
}): Promise<T>;
|
|
};
|
|
|
|
//abstract class for approving or rejecting a shift, expense, timesheet or pay-period
|
|
export abstract class BaseApprovalService<T> {
|
|
protected constructor(protected readonly prisma: PrismaPostgresService) {}
|
|
|
|
//returns the corresponding Prisma delegate
|
|
protected abstract get delegate(): UpdatableDelegate<T>;
|
|
|
|
protected abstract delegateFor(tx: Prisma.TransactionClient): UpdatableDelegate<T>;
|
|
|
|
//standard update Aproval
|
|
async updateApproval(id: number, is_approved: boolean): Promise<T> {
|
|
try{
|
|
return await this.delegate.update({
|
|
where: { id },
|
|
data: { is_approved: is_approved },
|
|
});
|
|
}catch (error: any) {
|
|
if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
|
|
throw new NotFoundException(`Entity #${id} not found`);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
//approval with transaction to avoid many requests
|
|
async updateApprovalWithTransaction(tx: Prisma.TransactionClient, id: number, is_approved: boolean): Promise<T> {
|
|
try {
|
|
return await this.delegateFor(tx).update({
|
|
where: { id },
|
|
data: { is_approved: is_approved },
|
|
});
|
|
} catch (error: any ){
|
|
if(error instanceof PrismaClientKnownRequestError && error.code === 'P2025') {
|
|
throw new NotFoundException(`Entity #${id} not found`);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
}
|