This commit is contained in:
Daniel
2026-04-01 20:06:17 +08:00
parent ae3e6f717b
commit afbcd99224
596 changed files with 62930 additions and 13 deletions

88
server.js Normal file
View File

@@ -0,0 +1,88 @@
const express = require("express");
const fs = require("fs/promises");
const path = require("path");
const crypto = require("crypto");
const app = express();
const PORT = process.env.PORT || 5180;
const DB_PATH = path.join(__dirname, "data", "shaders.json");
app.use(express.json({ limit: "1mb" }));
app.use(express.static(__dirname));
async function ensureDb() {
await fs.mkdir(path.dirname(DB_PATH), { recursive: true });
try {
await fs.access(DB_PATH);
} catch {
await fs.writeFile(DB_PATH, "[]", "utf8");
}
}
async function readDb() {
await ensureDb();
const raw = await fs.readFile(DB_PATH, "utf8");
return JSON.parse(raw);
}
async function writeDb(list) {
await ensureDb();
await fs.writeFile(DB_PATH, JSON.stringify(list, null, 2), "utf8");
}
app.get("/api/shaders", async (_req, res) => {
try {
const shaders = await readDb();
res.json(shaders);
} catch {
res.status(500).json({ error: "读取失败" });
}
});
app.post("/api/shaders", async (req, res) => {
const { name, author = "unknown", code } = req.body || {};
if (!name || typeof name !== "string") {
return res.status(400).json({ error: "name 必填" });
}
if (!code || typeof code !== "string" || !code.includes("mainImage")) {
return res.status(400).json({ error: "code 必须包含 mainImage" });
}
try {
const shaders = await readDb();
const item = {
id: crypto.randomUUID(),
name: name.trim(),
author: String(author || "unknown").trim() || "unknown",
code,
views: Math.floor(3000 + Math.random() * 22000),
likes: Math.floor(40 + Math.random() * 700),
createdAt: new Date().toISOString(),
};
shaders.unshift(item);
await writeDb(shaders);
res.status(201).json(item);
} catch {
res.status(500).json({ error: "保存失败" });
}
});
app.delete("/api/shaders/:id", async (req, res) => {
try {
const shaders = await readDb();
const next = shaders.filter((it) => it.id !== req.params.id);
if (next.length === shaders.length) {
return res.status(404).json({ error: "未找到该 shader" });
}
await writeDb(next);
res.status(204).end();
} catch {
res.status(500).json({ error: "删除失败" });
}
});
ensureDb().then(() => {
app.listen(PORT, () => {
console.log(`Server running: http://localhost:${PORT}`);
});
});