70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/lib/auth";
|
|
import { db } from "@/lib/db";
|
|
import { scheduledTasks } from "@/lib/db/schema";
|
|
import { scheduleTask, stopTask } from "@/lib/scheduler";
|
|
import { eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import cron from "node-cron";
|
|
|
|
const UpdateSchema = z.object({
|
|
name: z.string().min(1).max(100).optional(),
|
|
description: z.string().max(500).optional(),
|
|
cronExpression: z.string().max(100).optional(),
|
|
command: z.string().min(1).max(500).optional(),
|
|
isEnabled: z.boolean().optional(),
|
|
});
|
|
|
|
export async function PATCH(
|
|
req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
const session = await auth.api.getSession({ headers: req.headers });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
if (!["superadmin", "admin"].includes(session.user.role ?? "")) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
const task = await db.select().from(scheduledTasks).where(eq(scheduledTasks.id, id)).get();
|
|
if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
|
|
|
|
let body: z.infer<typeof UpdateSchema>;
|
|
try {
|
|
body = UpdateSchema.parse(await req.json());
|
|
} catch {
|
|
return NextResponse.json({ error: "Invalid request" }, { status: 400 });
|
|
}
|
|
|
|
if (body.cronExpression && !cron.validate(body.cronExpression)) {
|
|
return NextResponse.json({ error: "Invalid cron expression" }, { status: 400 });
|
|
}
|
|
|
|
const updated = { ...task, ...body, updatedAt: Date.now() };
|
|
await db.update(scheduledTasks).set(updated).where(eq(scheduledTasks.id, id));
|
|
|
|
// Reschedule
|
|
stopTask(id);
|
|
if (updated.isEnabled) {
|
|
scheduleTask(id, updated.cronExpression, updated.command);
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
}
|
|
|
|
export async function DELETE(
|
|
req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
const session = await auth.api.getSession({ headers: req.headers });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
if (!["superadmin", "admin"].includes(session.user.role ?? "")) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
stopTask(id);
|
|
await db.delete(scheduledTasks).where(eq(scheduledTasks.id, id));
|
|
return NextResponse.json({ success: true });
|
|
}
|