init
This commit is contained in:
80
app/api/v1/task/route.ts
Normal file
80
app/api/v1/task/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db";
|
||||
import { lobsters, tasks } from "@/lib/db/schema";
|
||||
import {
|
||||
incrementGlobalStat,
|
||||
incrementHourlyActivity,
|
||||
publishEvent,
|
||||
} from "@/lib/redis";
|
||||
import { validateApiKey } from "@/lib/auth/api-key";
|
||||
import { taskSchema } from "@/lib/validators/schemas";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const authHeader = req.headers.get("authorization");
|
||||
if (!authHeader?.startsWith("Bearer ")) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing or invalid authorization header" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const apiKey = authHeader.slice(7);
|
||||
const lobster = await validateApiKey(apiKey);
|
||||
if (!lobster) {
|
||||
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const parsed = taskSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validation failed", details: parsed.error.flatten() },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { summary, durationMs, model, toolsUsed } = parsed.data;
|
||||
const now = new Date();
|
||||
|
||||
const insertResult = await db.insert(tasks).values({
|
||||
lobsterId: lobster.id,
|
||||
summary,
|
||||
durationMs,
|
||||
model: model ?? null,
|
||||
toolsUsed: toolsUsed ?? null,
|
||||
timestamp: now,
|
||||
});
|
||||
|
||||
await db
|
||||
.update(lobsters)
|
||||
.set({ totalTasks: sql`${lobsters.totalTasks} + 1`, updatedAt: now })
|
||||
.where(eq(lobsters.id, lobster.id));
|
||||
|
||||
await incrementGlobalStat("total_tasks");
|
||||
await incrementGlobalStat("tasks_today");
|
||||
await incrementHourlyActivity();
|
||||
|
||||
await publishEvent({
|
||||
type: "task",
|
||||
lobsterId: lobster.id,
|
||||
lobsterName: lobster.name,
|
||||
city: lobster.city,
|
||||
country: lobster.country,
|
||||
summary,
|
||||
durationMs,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
taskId: insertResult[0].insertId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Task error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user