bearmetalpacker/main.ts
2024-10-18 20:10:43 -06:00

67 lines
1.9 KiB
TypeScript

import { SockpuppetPlus } from "@cgg/sockpuppet";
import { serveDir } from "@std/http/file-server";
import { BearMetalStore } from "@bearmetal/store";
const installPath = Deno.env.get("BMP_INSTALL_DIR") || "./";
const sockpuppet = new SockpuppetPlus();
sockpuppet.addHandler((req: Request) => {
if (new URL(req.url).pathname.startsWith("/api")) return;
return serveDir(req, {
fsRoot: installPath + "dist",
});
});
sockpuppet.addHandler(async (req: Request) => {
if (!new URL(req.url).pathname.startsWith("/api")) return;
const store = new BearMetalStore();
console.log("API", req.url);
const API_DIR_ROUTE = new URLPattern({
pathname: "/api/dir",
search: "?list",
});
const match = API_DIR_ROUTE.exec(req.url);
if (!match) return;
switch (req.method) {
case "GET": {
const mcPath = store.get("mcPath") as string;
if (mcPath) {
for await (const file of Deno.readDir(mcPath)) {
if (file.isDirectory && file.name.startsWith("saves")) {
const worlds: string[] = [];
for await (const world of Deno.readDir(mcPath + "/" + file.name)) {
if (world.isDirectory) {
worlds.push(world.name);
}
}
return new Response(JSON.stringify({ worlds, mcPath }), {
status: 200,
});
}
}
}
return new Response(JSON.stringify({ mcPath }), {
status: mcPath ? 200 : 500,
});
}
case "POST": {
const formData = await req.formData();
const dir = formData.get("dir") as string;
if (!dir) return new Response(null, { status: 400 });
Deno.env.set("MC_PATH", dir);
const mcPath = Deno.env.get("MC_PATH");
if (!mcPath) return new Response(null, { status: 500 });
return new Response(null, { status: 200 });
}
default:
return new Response(null, { status: 405 });
}
});