86 lines
2.5 KiB
TypeScript
86 lines
2.5 KiB
TypeScript
import type { APIRoute } from "astro";
|
|
import { isAuthed } from "../../../lib/session";
|
|
import {
|
|
getProjects,
|
|
setProjects,
|
|
getNotes,
|
|
setNotes,
|
|
type Project,
|
|
} from "../../../lib/content";
|
|
|
|
export const prerender = false;
|
|
|
|
const back = () =>
|
|
new Response(null, { status: 303, headers: { Location: "/admin" } });
|
|
|
|
function projectFromForm(form: FormData, id: string): Project {
|
|
const s = (k: string) => String(form.get(k) ?? "").trim();
|
|
return {
|
|
id,
|
|
title: s("title"),
|
|
blurb: s("blurb"),
|
|
year: s("year"),
|
|
href: s("href") || undefined,
|
|
repo: s("repo") || undefined,
|
|
tags: s("tags")
|
|
.split(",")
|
|
.map((t) => t.trim().replace(/^#/, ""))
|
|
.filter(Boolean),
|
|
featured: form.get("featured") != null,
|
|
draft: form.get("draft") != null,
|
|
};
|
|
}
|
|
|
|
export const POST: APIRoute = async ({ request }) => {
|
|
if (!(await isAuthed(request))) return back();
|
|
|
|
const form = await request.formData();
|
|
const action = String(form.get("action") ?? "");
|
|
|
|
if (action === "note-save") {
|
|
const body = String(form.get("body") ?? "").trim();
|
|
if (!body) return back();
|
|
const id = String(form.get("id") ?? "").trim();
|
|
const notes = await getNotes();
|
|
const i = notes.findIndex((x) => x.id === id);
|
|
if (i >= 0) {
|
|
notes[i] = { ...notes[i], body };
|
|
} else {
|
|
notes.unshift({ id: crypto.randomUUID().slice(0, 8), body, date: new Date().toISOString() });
|
|
}
|
|
await setNotes(notes);
|
|
return back();
|
|
} else if (action === "note-delete") {
|
|
const id = String(form.get("id") ?? "");
|
|
await setNotes((await getNotes()).filter((x) => x.id !== id));
|
|
return back();
|
|
}
|
|
|
|
const list = await getProjects();
|
|
|
|
if (action === "project-save") {
|
|
const id =
|
|
String(form.get("id") ?? "").trim() || crypto.randomUUID().slice(0, 8);
|
|
const p = projectFromForm(form, id);
|
|
if (!p.title) return back();
|
|
const i = list.findIndex((x) => x.id === id);
|
|
if (i >= 0) list[i] = p;
|
|
else list.push(p);
|
|
await setProjects(list);
|
|
} else if (action === "project-delete") {
|
|
const id = String(form.get("id") ?? "");
|
|
await setProjects(list.filter((x) => x.id !== id));
|
|
} else if (action === "project-move") {
|
|
const id = String(form.get("id") ?? "");
|
|
const dir = String(form.get("dir") ?? "");
|
|
const i = list.findIndex((x) => x.id === id);
|
|
const j = dir === "up" ? i - 1 : i + 1;
|
|
if (i >= 0 && j >= 0 && j < list.length) {
|
|
[list[i], list[j]] = [list[j], list[i]];
|
|
await setProjects(list);
|
|
}
|
|
}
|
|
|
|
return back();
|
|
};
|