feat: add Appwrite TablesDB content importer

Idempotent upsert of src/content markdown into the spaghet-home
TablesDB database (blog/projects/work/legal) on appwrite.spaghet.io,
as part of the .md -> Appwrite documents migration.

Pivoted from the DocumentsDB capability: self-hosted Appwrite 2.7.4
gates its console UI ('feature not available on the current console
version'), so content management needs the TablesDB UI instead.
TablesDB also gives working per-column fulltext indexes and runs on
the shared PostgreSQL container.
This commit is contained in:
spaghet committed 2026-11-26 18:16:54 -05:00
1 parent d7b8a351c1
commit 2b775cbf99
1 file changed
+117
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env node
/**
* Import (and re-sync) the markdown content in src/content/* into the
* `spaghet-home` TablesDB database on appwrite.spaghet.io.
*
* Tables (schema, created once via API/console): blog, projects, work, legal.
* The frontmatter fields become row columns, the markdown body becomes the
* `content` column (mediumtext), and the filename (minus .md) is both the
* row $id and the `slug` column. Dates are sent as ISO 8601 UTC.
*
* Usage:
* APPWRITE_API_KEY=*** node scripts/appwrite-migrate.mjs [--collection blog]
*
* The key needs scopes: databases.read/write, tables.read/write,
* rows.read/write. It is sent as the x-appwrite-key header (server SDK
* auth; Bearer works for reads but this instance rejects it for writes).
*
* Idempotent: each file is upserted (create, fall back to update on 409).
* Run it again after editing any .md to push changes to Appwrite.
*
* NOTE: this script is the migration/backup path. Once src/lib/appwrite.ts
* serves reads, Appwrite is the source of truth for published content and
* this script only needs to run when you deliberately re-import.
*/
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
const ENDPOINT = process.env.APPWRITE_ENDPOINT ?? "https://appwrite.spaghet.io/v1";
const PROJECT = process.env.APPWRITE_PROJECT_ID ?? "homelab";
const DATABASE = process.env.APPWRITE_DATABASE_ID ?? "spaghet-home";
const KEY = process.env.APPWRITE_API_KEY;
if (!KEY) throw new Error("APPWRITE_API_KEY is required (tablesdb-scoped key)");
const COLLECTIONS = ["blog", "projects", "work", "legal"];
// --- frontmatter -------------------------------------------------------
function parseFrontmatter(raw) {
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
if (!m) return { data: {}, body: raw };
const data = {};
for (const line of m[1].split(/\r?\n/)) {
if (!line.trim()) continue;
const idx = line.indexOf(":");
if (idx === -1) continue;
const key = line.slice(0, idx).trim();
let value = line.slice(idx + 1).trim();
if (value.startsWith("[") && value.endsWith("]")) {
data[key] = value
.slice(1, -1)
.split(",")
.map((s) => s.trim().replace(/^["']|["']$/g, ""))
.filter(Boolean);
} else if (value === "true" || value === "false") {
data[key] = value === "true";
} else if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
data[key] = `${value}T00:00:00.000Z`; // Appwrite datetime
} else {
data[key] = value.replace(/^["']|["']$/g, "");
}
}
return { data, body: m[2] };
}
// --- Appwrite REST -----------------------------------------------------
async function api(method, url, body) {
const res = await fetch(url, {
method,
headers: {
"x-appwrite-key": KEY,
"x-appwrite-project": PROJECT,
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await res.text();
let json;
try {
json = JSON.parse(text);
} catch {
json = { message: text };
}
return { status: res.status, json };
}
const base = path.resolve(import.meta.dirname, "..", "src", "content");
const only = (() => {
const i = process.argv.indexOf("--collection");
return i !== -1 ? process.argv[i + 1] : null;
})();
let created = 0, updated = 0, failed = 0;
for (const coll of COLLECTIONS) {
if (only && only !== coll) continue;
const files = (await readdir(path.join(base, coll))).filter((f) => f.endsWith(".md")).sort();
for (const file of files) {
const slug = file.replace(/\.md$/, "");
const raw = await readFile(path.join(base, coll, file), "utf8");
const { data, body } = parseFrontmatter(raw);
const row = { slug, content: body.trim() + "\n", ...data };
const url = `${ENDPOINT}/tablesdb/${DATABASE}/tables/${coll}/rows`;
let res = await api("POST", url, { rowId: slug, data: row });
if (res.status === 201) {
created++;
} else if (res.status === 409) {
res = await api("PUT", `${url}/${encodeURIComponent(slug)}`, { data: row });
if (res.status === 200) updated++;
}
if (res.status >= 400) {
failed++;
console.error(`${coll}/${slug}: ${res.status} ${res.json.message ?? ""}`);
} else {
console.log(`${coll}/${slug}: ok`);
}
}
}
console.log(`\ncreated=${created} updated=${updated} failed=${failed}`);
process.exit(failed ? 1 : 0);