Files
var-monorepo/apps/dispatch/app/api/position-log/route.ts
2025-06-30 13:37:42 -07:00

74 lines
1.7 KiB
TypeScript

import { PositionLog, Prisma, prisma, User } from "@repo/db";
import { getServerSession } from "api/auth/[...nextauth]/auth";
import { verify } from "jsonwebtoken";
export const PUT = async (req: Request) => {
const session = await getServerSession();
const token = req.headers.get("authorization")?.split(" ")[1];
if (!token) return Response.json({ message: "Missing token" }, { status: 401 });
const payload = await new Promise<User>((resolve, reject) => {
verify(token, process.env.AUTH_HUB_SECRET as string, (err, decoded) => {
if (err) {
reject(err);
} else {
resolve(decoded as User);
}
});
});
if (!session && !payload) return Response.json({ message: "Unauthorized" }, { status: 401 });
const userId = session?.user.id || payload.id;
const { position, h145 } = (await req.json()) as {
position: PositionLog;
h145: boolean;
};
if (!position) {
return Response.json({ message: "Missing id or position" });
}
const activeAircraft = await prisma.connectedAircraft.findFirst({
where: {
userId,
logoutTime: null,
},
orderBy: {
loginTime: "desc",
},
select: {
id: true,
},
});
if (!activeAircraft) {
return Response.json({ message: "No active aircraft found" }, { status: 400 });
}
const positionLog = await prisma.positionLog.create({
data: {
...position,
connectedAircraftId: activeAircraft.id,
userId,
},
});
await prisma.connectedAircraft.update({
where: {
id: activeAircraft?.id,
},
data: {
userId,
lastHeartbeat: new Date(),
posAlt: positionLog.alt,
posLat: positionLog.lat,
posLng: positionLog.lng,
posHeading: positionLog.heading,
posSpeed: positionLog.speed,
posH145active: h145,
},
});
return Response.json(positionLog);
};