Bucket site-media (project homelab) holds public/images/{logo.png,
profile.jpg} under stable file ids equal to the filenames, read("any")
so browsers fetch them keyless. src/lib/media.ts builds the /view and
/preview URLs; the profile circle uses preview width=256 (Appwrite resize
44 KB -> 10 KB webp/jpeg, cached on the storage layer with a 45-day
expiry). Each img keeps onerror swap to the public/images/ copy, which
stays in git as upload source and outage fallback.
Importer now upserts media too (size-match skip, delete+recreate on
change). Server-side note: _APP_STORAGE_LIMIT was unset (0), which
made every upload fail 'File size not allowed' and stored 0 in new
buckets' maximumFileSize; set to 30 MiB in .env + recreate, and the
bucket updated to match. Console storage UI verified rendering on
self-hosted 2.7.4 (unlike documentsdb).
156 lines
6.0 KiB
JavaScript
156 lines
6.0 KiB
JavaScript
#!/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`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- media (public/images/*.{png,jpg,jpeg,webp}) --------------------------
|
|
// Files are upserted under stable IDs equal to the filename, so a re-import
|
|
// replaces bytes rather than piling up versions. The bucket (`site-media`)
|
|
// must exist with read("any") and a non-zero maximumFileSize; create it once
|
|
// from the console or the API.
|
|
if (!only) {
|
|
const BUCKET = process.env.APPWRITE_BUCKET_ID ?? "site-media";
|
|
const imgDir = path.resolve(import.meta.dirname, "..", "public", "images");
|
|
const images = (await readdir(imgDir)).filter((f) => /\.(png|jpe?g|webp)$/i.test(f)).sort();
|
|
for (const file of images) {
|
|
const buf = await readFile(path.join(imgDir, file));
|
|
const existing = await api("GET", `${ENDPOINT}/storage/buckets/${BUCKET}/files/${encodeURIComponent(file)}`);
|
|
if (existing.status === 200 && existing.json.sizeOriginal === buf.length) {
|
|
console.log(`media/${file}: unchanged`);
|
|
continue;
|
|
}
|
|
if (existing.status === 200) {
|
|
// No content-replace endpoint: delete, then re-create with the same id.
|
|
await api("DELETE", `${ENDPOINT}/storage/buckets/${BUCKET}/files/${encodeURIComponent(file)}`);
|
|
}
|
|
const form = new FormData();
|
|
form.append("fileId", file);
|
|
form.append("fileUpload", new Blob([buf]), file);
|
|
const res = await fetch(`${ENDPOINT}/storage/buckets/${BUCKET}/files`, {
|
|
method: "POST",
|
|
headers: { "x-appwrite-key": KEY, "x-appwrite-project": PROJECT },
|
|
body: form,
|
|
});
|
|
if (res.status === 201) {
|
|
console.log(`media/${file}: uploaded (${buf.length} bytes)`);
|
|
} else {
|
|
failed++;
|
|
console.error(`media/${file}: ${res.status} ${(await res.text()).slice(0, 120)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(`\ncreated=${created} updated=${updated} failed=${failed}`);
|
|
process.exit(failed ? 1 : 0);
|