Refactor index.ts: streamline server setup, integrate routing, and add error handling middleware. Removed unused code and initialized cron jobs.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import ActiveSession from "../models/ActiveSession";
|
||||
import got from "got-cjs";
|
||||
import { differenceInMinutes, isAfter } from "date-fns";
|
||||
|
||||
export async function checkActiveSessions() {
|
||||
const activeSessions = await ActiveSession.find();
|
||||
|
||||
for (const activeSession of activeSessions) {
|
||||
if (
|
||||
!activeSession.endAt &&
|
||||
!activeSession.connectedPlayersCount &&
|
||||
differenceInMinutes(new Date(), activeSession.updatedAt) >= 3
|
||||
) {
|
||||
const activeSessionId = activeSession.id;
|
||||
|
||||
try {
|
||||
const result = await got
|
||||
.post(
|
||||
`https://${activeSession.location}.sess.stream.graff.tech/server/${activeSession.localIP}:3000/end`,
|
||||
{ json: { activeSessionId } }
|
||||
)
|
||||
.json();
|
||||
|
||||
console.log("Result:", result);
|
||||
} catch (error) {
|
||||
console.log({ error });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkScheduledSessions() {
|
||||
try {
|
||||
const scheduledSessions: any = await got
|
||||
.get(`${process.env.CRM_API_URL}/scheduledSessions`)
|
||||
.json();
|
||||
|
||||
if (!scheduledSessions.length) return;
|
||||
|
||||
for (const session of scheduledSessions) {
|
||||
if (
|
||||
isAfter(new Date(), new Date(session.startAt)) &&
|
||||
!session.activeSessionId
|
||||
) {
|
||||
console.log("session.buildId", session.buildId);
|
||||
const { build }: any = await got
|
||||
.get(`${process.env.CRM_API_URL}/builds/${session.buildId}`)
|
||||
.json();
|
||||
|
||||
console.log("build", build);
|
||||
|
||||
const result: any = await got
|
||||
.get(
|
||||
`https://coord.graff.tech/start?build=${build}&location=a1&type=prod&endAt=${session.endAt}`
|
||||
)
|
||||
.json();
|
||||
|
||||
if (!result.stream) {
|
||||
console.log("Not result.stream");
|
||||
return;
|
||||
}
|
||||
|
||||
const result2 = await got
|
||||
.put(`${process.env.CRM_API_URL}/scheduledSessions/${session.id}`, {
|
||||
json: {
|
||||
activeSessionId: result.stream,
|
||||
},
|
||||
})
|
||||
.json();
|
||||
|
||||
console.log("result2: ", result2);
|
||||
} else if (isAfter(new Date(), new Date(session.endAt))) {
|
||||
const result = await got
|
||||
.post(`https://coord.graff.tech/end`, {
|
||||
json: { activeSessionId: session.activeSessionId },
|
||||
})
|
||||
.json();
|
||||
|
||||
console.log("CRON End active session: ", result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("Error: ", (error as Error).message);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user