Save and load scripts

This commit is contained in:
2025-11-03 16:55:46 -08:00
parent 684ae0ecf8
commit 30649488bb
7 changed files with 412 additions and 5 deletions

View File

@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises";
import { join } from "path";
import { existsSync } from "fs";
import { SAVE_CONFIG } from "@/lib/saveConfig";
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const name = searchParams.get("name");
if (!name) {
return NextResponse.json(
{ error: "Script name is required" },
{ status: 400 }
);
}
// Validate filename (same validation as save)
if (!SAVE_CONFIG.FILENAME_REGEX.test(name)) {
return NextResponse.json(
{ error: "Invalid script name" },
{ status: 400 }
);
}
const saveDir = join(process.cwd(), SAVE_CONFIG.SAVE_DIRECTORY);
const filename = `${name}.rhai`;
const filepath = join(saveDir, filename);
// Check if file exists
if (!existsSync(filepath)) {
return NextResponse.json(
{ error: `Script "${name}" not found` },
{ status: 404 }
);
}
// Read and return file content
const content = await readFile(filepath, "utf8");
return NextResponse.json({
name,
filename,
content,
});
} catch (error) {
console.error("Get script error:", error);
return NextResponse.json(
{ error: "Failed to read script" },
{ status: 500 }
);
}
}