feat(storage): move project data to SQLite via node:sqlite
- server/db.mjs: schema (site + projects), transactional replace, WAL, VACUUM INTO backups (keep 10), JSON export, first-run seed from data/projects.json - publish.mjs: read/write through the database, export mirror JSON for git/static/offline, validate duplicate project_id - ui/data.js: read live data from /api/projects first, fall back to data/projects.json - Dockerfile/compose/.env.example: DB_PATH, drop experimental sqlite warning flag - docs: AGENTS.md + README describe the database layer and traps
This commit is contained in:
1 parent
830dba58ec
commit
5fb095b872
11 files changed
+364
-61
No files matched your search
+44
-39
@@ -2,14 +2,17 @@
|
||||
/**
|
||||
* server/publish.mjs — เซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency ภายนอก)
|
||||
*
|
||||
* GET /api/projects อ่านข้อมูลปัจจุบัน
|
||||
* PUT /api/projects เขียน data/projects.json แล้ว commit + push ขึ้น Gitea
|
||||
* GET /api/projects อ่านข้อมูลปัจจุบันจาก SQLite
|
||||
* PUT /api/projects เขียนลง SQLite → export data/projects.json → commit + push ขึ้น Gitea
|
||||
* static เสิร์ฟไฟล์หน้าเว็บจาก root ของโปรเจค
|
||||
*
|
||||
* ข้อมูลจริงอยู่ใน `data/hobbypj.sqlite` (SQLite ผ่าน node:sqlite, override ด้วย DB_PATH)
|
||||
* `data/projects.json` เป็นสำเนาที่ export ออกมาทุกครั้งที่บันทึก
|
||||
*
|
||||
* ใช้งาน:
|
||||
* node server/publish.mjs # http://localhost:8090
|
||||
* PORT=8090 ADMIN_TOKEN=xxxx node server/publish.mjs
|
||||
* PUBLISH_PUSH=0 node server/publish.mjs # เขียนไฟล์ + commit แต่ไม่ push
|
||||
* PUBLISH_PUSH=0 node server/publish.mjs # เขียน + commit แต่ไม่ push
|
||||
*
|
||||
* ความปลอดภัย:
|
||||
* - ถ้าตั้ง ADMIN_TOKEN ไว้ ต้องส่ง header x-admin-token ให้ตรงทุกครั้งที่เขียน
|
||||
@@ -17,17 +20,28 @@
|
||||
*/
|
||||
|
||||
import { createServer } from "node:http";
|
||||
import { readFile, stat, writeFile, mkdir } from "node:fs/promises";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
backupDatabase,
|
||||
countProjects,
|
||||
exportJson,
|
||||
openDatabase,
|
||||
readData,
|
||||
resolveDbPath,
|
||||
saveData,
|
||||
seedFromJson,
|
||||
} from "./db.mjs";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, "..");
|
||||
const DATA_FILE = path.join(ROOT, "data", "projects.json");
|
||||
const DB_FILE = resolveDbPath(ROOT);
|
||||
const PORT = Number(process.env.PORT || 8090);
|
||||
const HOST = process.env.HOST || "0.0.0.0";
|
||||
const ADMIN_TOKEN = (process.env.ADMIN_TOKEN || "").trim();
|
||||
@@ -94,6 +108,7 @@ function validate(payload) {
|
||||
errors.push("projects ต้องเป็น array");
|
||||
return errors;
|
||||
}
|
||||
const seen = new Set();
|
||||
payload.projects.forEach((project, index) => {
|
||||
const label = `รายการที่ ${index + 1}`;
|
||||
if (!project || typeof project !== "object") {
|
||||
@@ -106,32 +121,14 @@ function validate(payload) {
|
||||
errors.push(`${label}: ลิงก์ไม่ถูกต้อง (${url || "ว่าง"})`);
|
||||
if (project.contact_email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(project.contact_email).trim()))
|
||||
errors.push(`${label}: อีเมลไม่ถูกต้อง`);
|
||||
const id = String(project.project_id || "").trim();
|
||||
if (!id) errors.push(`${label}: ไม่มีรหัสโปรเจค (project_id)`);
|
||||
else if (seen.has(id)) errors.push(`${label}: รหัสโปรเจคซ้ำ (${id})`);
|
||||
else seen.add(id);
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
/** เขียน payload ให้คีย์เรียงคงที่ อ่านง่ายแบบมนุษย์ + ลงท้ายด้วย newline */
|
||||
function serialize(payload) {
|
||||
const ordered = {
|
||||
schema_version: 1,
|
||||
updated_at: payload.updated_at,
|
||||
owner_name: payload.owner_name || "",
|
||||
site: {
|
||||
site_title: payload.site.site_title || "",
|
||||
welcome_message: payload.site.welcome_message || "",
|
||||
},
|
||||
projects: payload.projects.map((project) => ({
|
||||
project_id: String(project.project_id || "").trim(),
|
||||
project_name: String(project.project_name || "").trim(),
|
||||
project_description: String(project.project_description || "").trim(),
|
||||
project_url: String(project.project_url || "").trim().replace(/\/$/, ""),
|
||||
contact_email: String(project.contact_email || "").trim(),
|
||||
icon: String(project.icon || "folder").trim(),
|
||||
})),
|
||||
};
|
||||
return `${JSON.stringify(ordered, null, 2)}\n`;
|
||||
}
|
||||
|
||||
async function gitPublish() {
|
||||
const rel = path.relative(ROOT, DATA_FILE);
|
||||
const result = { committed: false, pushed: false, commit: null, message: "" };
|
||||
@@ -170,18 +167,12 @@ async function gitPublish() {
|
||||
}
|
||||
}
|
||||
|
||||
async function readData() {
|
||||
const raw = await readFile(DATA_FILE, "utf8");
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
async function handleApi(req, res, pathname) {
|
||||
if (pathname === "/api/projects" && req.method === "GET") {
|
||||
try {
|
||||
const data = await readData();
|
||||
sendJson(res, 200, { ok: true, writable: canWrite(req) || isLoopback(req), data });
|
||||
sendJson(res, 200, { ok: true, writable: canWrite(req) || isLoopback(req), data: readData(db) });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { ok: false, error: `อ่านไฟล์ข้อมูลไม่ได้: ${error.message}` });
|
||||
sendJson(res, 500, { ok: false, error: `อ่านฐานข้อมูลไม่ได้: ${error.message}` });
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -215,11 +206,13 @@ async function handleApi(req, res, pathname) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
payload.updated_at = new Date().toISOString();
|
||||
await mkdir(path.dirname(DATA_FILE), { recursive: true });
|
||||
await writeFile(DATA_FILE, serialize(payload), "utf8");
|
||||
// สำรองสภาพก่อนแก้ (ถ้ามีข้อมูลอยู่) แล้วค่อยเขียนทับในทรานแซกชันเดียว
|
||||
const backup = countProjects(db) > 0 ? await backupDatabase(db, DB_FILE).catch(() => null) : null;
|
||||
payload.updated_at = saveData(db, payload);
|
||||
await exportJson(DATA_FILE, { ...payload, updated_at: payload.updated_at });
|
||||
payload.backup = backup ? path.relative(ROOT, backup) : null;
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { ok: false, error: `เขียนไฟล์ไม่ได้: ${error.message}` });
|
||||
sendJson(res, 500, { ok: false, error: `เขียนฐานข้อมูลไม่ได้: ${error.message}` });
|
||||
return;
|
||||
}
|
||||
const git = await gitPublish();
|
||||
@@ -227,6 +220,7 @@ async function handleApi(req, res, pathname) {
|
||||
ok: true,
|
||||
updated_at: payload.updated_at,
|
||||
projects: payload.projects.length,
|
||||
database: path.relative(ROOT, DB_FILE),
|
||||
git,
|
||||
});
|
||||
return;
|
||||
@@ -275,6 +269,10 @@ async function serveStatic(req, res, pathname) {
|
||||
}
|
||||
}
|
||||
|
||||
// เปิดฐานข้อมูล + ย้ายข้อมูลจาก data/projects.json ครั้งแรก (ถ้าตารางว่าง)
|
||||
const db = await openDatabase(DB_FILE);
|
||||
const seed = await seedFromJson(db, DATA_FILE);
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
||||
if (req.method === "OPTIONS") {
|
||||
@@ -296,5 +294,12 @@ server.listen(PORT, HOST, () => {
|
||||
const writable = ADMIN_TOKEN ? "เฉพาะผู้มีรหัสเผยแพร่" : "เฉพาะเครื่องนี้ (ยังไม่ตั้ง ADMIN_TOKEN)";
|
||||
console.log(`[hobbypj] เซิร์ฟเวอร์ทำงานที่ http://localhost:${PORT}`);
|
||||
console.log(`[hobbypj] เขียนข้อมูลได้: ${writable}`);
|
||||
console.log(`[hobbypj] ไฟล์ข้อมูล: ${path.relative(ROOT, DATA_FILE)} · push: ${SHOULD_PUSH ? "เปิด" : "ปิด"}`);
|
||||
console.log(
|
||||
`[hobbypj] ฐานข้อมูล: ${path.relative(ROOT, DB_FILE)} (SQLite) · สำเนา JSON: ${path.relative(ROOT, DATA_FILE)} · push: ${SHOULD_PUSH ? "เปิด" : "ปิด"}`,
|
||||
);
|
||||
console.log(
|
||||
seed.seeded
|
||||
? `[hobbypj] ย้ายข้อมูลจาก projects.json เข้าฐานข้อมูลแล้ว ${seed.count} รายการ`
|
||||
: `[hobbypj] ฐานข้อมูลพร้อมใช้ (${seed.reason})`,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user