Files
DentalManagementMH06/apps/Backend/src/storage/cron-job-log-storage.ts

62 lines
1.6 KiB
TypeScript

import { prisma as db } from "@repo/db/client";
export type CronJobStatus = "success" | "failed" | "skipped";
export interface CronJobLogEntry {
id: number;
jobName: string;
status: string;
startedAt: Date;
completedAt: Date | null;
durationMs: number | null;
errorMessage: string | null;
}
export const cronJobLogStorage = {
async createJobLog(
jobName: string,
startedAt: Date
): Promise<CronJobLogEntry> {
return db.cronJobLog.create({
data: { jobName, status: "running", startedAt },
});
},
async completeJobLog(
id: number,
status: CronJobStatus,
completedAt: Date,
errorMessage?: string
): Promise<CronJobLogEntry> {
const durationMs = completedAt.getTime() - (await db.cronJobLog.findUniqueOrThrow({ where: { id } })).startedAt.getTime();
return db.cronJobLog.update({
where: { id },
data: { status, completedAt, durationMs, errorMessage: errorMessage ?? null },
});
},
async getRecentLogs(limit = 50): Promise<CronJobLogEntry[]> {
return db.cronJobLog.findMany({
orderBy: { startedAt: "desc" },
take: limit,
});
},
async getLastRunPerJob(): Promise<CronJobLogEntry[]> {
// Get the most recent log entry for each distinct jobName
const jobs = await db.cronJobLog.findMany({
distinct: ["jobName"],
orderBy: { startedAt: "desc" },
});
return jobs;
},
async getFailedLogs(limit = 20): Promise<CronJobLogEntry[]> {
return db.cronJobLog.findMany({
where: { status: "failed" },
orderBy: { startedAt: "desc" },
take: limit,
});
},
};