74 lines
2.1 KiB
TypeScript
74 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { eq, desc, sql, and } from "drizzle-orm";
|
|
import { db } from "@/lib/db";
|
|
import { lobsters, tasks } from "@/lib/db/schema";
|
|
import { getActiveLobsterIds } from "@/lib/redis";
|
|
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(req.url);
|
|
const limitParam = parseInt(searchParams.get("limit") ?? "50", 10);
|
|
const limit = Math.min(Math.max(1, limitParam), 200);
|
|
const region = searchParams.get("region");
|
|
|
|
const conditions = [];
|
|
if (region) {
|
|
conditions.push(eq(lobsters.region, region));
|
|
}
|
|
|
|
const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
|
|
|
|
const lobsterRows = await db
|
|
.select()
|
|
.from(lobsters)
|
|
.where(whereClause)
|
|
.orderBy(desc(lobsters.lastHeartbeat))
|
|
.limit(limit);
|
|
|
|
const totalResult = await db
|
|
.select({ count: sql<number>`count(*)` })
|
|
.from(lobsters)
|
|
.where(whereClause);
|
|
const total = totalResult[0]?.count ?? 0;
|
|
|
|
const activeLobsterIds = await getActiveLobsterIds();
|
|
const activeSet = new Set(activeLobsterIds);
|
|
|
|
const lobsterList = await Promise.all(
|
|
lobsterRows.map(async (lobster) => {
|
|
const latestTaskRows = await db
|
|
.select({
|
|
summary: tasks.summary,
|
|
timestamp: tasks.timestamp,
|
|
durationMs: tasks.durationMs,
|
|
})
|
|
.from(tasks)
|
|
.where(eq(tasks.lobsterId, lobster.id))
|
|
.orderBy(desc(tasks.timestamp))
|
|
.limit(1);
|
|
|
|
const lastTask = latestTaskRows[0] ?? null;
|
|
|
|
return {
|
|
id: lobster.id,
|
|
name: lobster.name,
|
|
model: lobster.model,
|
|
platform: lobster.platform,
|
|
city: lobster.city,
|
|
country: lobster.country,
|
|
isOnline: activeSet.has(lobster.id),
|
|
lastTask,
|
|
};
|
|
})
|
|
);
|
|
|
|
return NextResponse.json({ lobsters: lobsterList, total });
|
|
} catch (error) {
|
|
console.error("Lobsters error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|