added chronjob to clean up missions
This commit is contained in:
@@ -13,6 +13,7 @@ import { handleConnectDesktop } from "socket-events/connect-desktop";
|
||||
import cookieParser from "cookie-parser";
|
||||
import cors from "cors";
|
||||
import { authMiddleware } from "modules/expressMiddleware";
|
||||
import "modules/chron";
|
||||
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { MissionLog, prisma } from "@repo/db";
|
||||
import chron from "cron";
|
||||
|
||||
const removeClosedMissions = async () => {
|
||||
const oldMissions = await prisma.mission.findMany({
|
||||
where: {
|
||||
state: "running",
|
||||
},
|
||||
});
|
||||
oldMissions.forEach(async (mission) => {
|
||||
const lastAlert = (mission.missionLog as unknown as MissionLog[]).find((l) => {
|
||||
return l.type === "alert-log";
|
||||
});
|
||||
const lastAlertTime = lastAlert ? new Date(lastAlert.timeStamp) : null;
|
||||
|
||||
const now = new Date();
|
||||
if (!lastAlertTime) return;
|
||||
// change State to closed if last alert was more than 120 minutes ago
|
||||
if (lastAlertTime && now.getTime() - lastAlertTime.getTime() > 120 * 60 * 1000) {
|
||||
const log: MissionLog = {
|
||||
type: "completed-log",
|
||||
auto: true,
|
||||
timeStamp: new Date().toISOString(),
|
||||
data: {},
|
||||
};
|
||||
|
||||
await prisma.mission.update({
|
||||
where: {
|
||||
id: mission.id,
|
||||
},
|
||||
data: {
|
||||
state: "finished",
|
||||
missionLog: {
|
||||
push: log as any,
|
||||
},
|
||||
},
|
||||
});
|
||||
console.log(`Mission ${mission.id} closed due to inactivity.`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const removeClosedMissionsJob = new chron.CronJob(
|
||||
"*/5 * * * *", // Every 5 minutes
|
||||
removeClosedMissions,
|
||||
null,
|
||||
true,
|
||||
"Europe/Berlin",
|
||||
);
|
||||
|
||||
removeClosedMissionsJob.start();
|
||||
|
||||
Reference in New Issue
Block a user