2026-09-10 18:01:25 +07:00
|
|
|
// Sync ตาราง files กับไฟล์จริงใน public/samples/ (idempotent — รันซ้ำได้ทุกครั้ง)
|
2026-09-15 14:12:51 +07:00
|
|
|
// - INSERT ไฟล์ .pdf/.jpg/.jpeg/.png/.tif/.tiff ที่ยังไม่มี row (pdf_url = /samples/<ชื่อไฟล์> — N3)
|
|
|
|
|
// (สำเนารายการ extension นี้ต้อง sync กับ SAMPLE_FILE_EXTENSIONS ใน utils/file-kind.ts)
|
2026-09-10 18:01:25 +07:00
|
|
|
// - DELETE row ที่ชี้ /samples/* แต่ไฟล์หายจาก disk (CASCADE ลบ annotation/bookmark ตาม)
|
|
|
|
|
// รันตอน container start ต่อจาก migrate.mjs และรันมือบนเครื่อง dev ได้ผ่าน npm run seed-samples
|
|
|
|
|
import fs from "node:fs";
|
|
|
|
|
import path from "node:path";
|
|
|
|
|
import postgres from "postgres";
|
|
|
|
|
|
|
|
|
|
const SAMPLES_DIR = path.join(process.cwd(), "public", "samples");
|
|
|
|
|
|
2026-09-15 14:12:51 +07:00
|
|
|
// ต้องตรงกับ SAMPLE_FILE_EXTENSIONS ใน utils/file-kind.ts (script .mjs import TS ไม่ได้)
|
|
|
|
|
const SAMPLE_FILE_EXTENSIONS = [".pdf", ".jpg", ".jpeg", ".png", ".tif", ".tiff"];
|
|
|
|
|
|
2026-09-10 18:01:25 +07:00
|
|
|
const dbUrl = process.env.DATABASE_URL;
|
|
|
|
|
if (!dbUrl) throw new Error("ต้องตั้ง DATABASE_URL ก่อนรัน seed-samples");
|
|
|
|
|
|
|
|
|
|
const sql = postgres(dbUrl, { prepare: false, max: 1 });
|
|
|
|
|
try {
|
|
|
|
|
const onDisk = fs
|
|
|
|
|
.readdirSync(SAMPLES_DIR)
|
2026-09-15 14:12:51 +07:00
|
|
|
.filter((f) => SAMPLE_FILE_EXTENSIONS.some((ext) => f.toLowerCase().endsWith(ext)))
|
2026-09-10 18:01:25 +07:00
|
|
|
.map((f) => ({ title: f, pdfUrl: `/samples/${f}` }));
|
|
|
|
|
const diskUrls = new Set(onDisk.map((f) => f.pdfUrl));
|
|
|
|
|
|
|
|
|
|
const rows = await sql`select id, title, pdf_url from files where pdf_url like '/samples/%'`;
|
|
|
|
|
const dbUrls = new Set(rows.map((r) => r.pdf_url));
|
|
|
|
|
|
|
|
|
|
for (const file of onDisk) {
|
|
|
|
|
if (dbUrls.has(file.pdfUrl)) continue;
|
|
|
|
|
console.log(`[seed] เพิ่ม ${file.pdfUrl}`);
|
|
|
|
|
await sql`insert into files (title, pdf_url) values (${file.title}, ${file.pdfUrl})`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
if (diskUrls.has(row.pdf_url)) continue;
|
|
|
|
|
console.log(`[seed] ลบ ${row.pdf_url} (ไฟล์หายจาก image — annotation ที่ผูกอยู่ CASCADE ตามไปด้วย)`);
|
|
|
|
|
await sql`delete from files where id = ${row.id}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(`[seed] sync เสร็จ: ${onDisk.length} ไฟล์ใน samples`);
|
|
|
|
|
} finally {
|
|
|
|
|
await sql.end();
|
|
|
|
|
}
|