59 lines
1.4 KiB
TypeScript
59 lines
1.4 KiB
TypeScript
import {
|
|
createDocument,
|
|
Document,
|
|
getDocument,
|
|
getDocuments,
|
|
transformDocument,
|
|
} from "@lib/documents.ts";
|
|
import { Root } from "https://esm.sh/remark-frontmatter@4.0.1";
|
|
|
|
export function createCrud<T>(
|
|
{ prefix, parse }: {
|
|
prefix: string;
|
|
parse: (doc: string, id: string) => T;
|
|
},
|
|
) {
|
|
function pathFromId(id: string) {
|
|
return `${prefix}${id.replaceAll(":", "")}.md`;
|
|
}
|
|
|
|
async function read(id: string) {
|
|
const path = pathFromId(id);
|
|
const content = await getDocument(path);
|
|
|
|
return parse(content, id);
|
|
}
|
|
function create(id: string, content: string | ArrayBuffer) {
|
|
const path = pathFromId(id);
|
|
return createDocument(path, content);
|
|
}
|
|
|
|
async function update(id: string, updater: (r: Root) => Root) {
|
|
const path = pathFromId(id);
|
|
const content = await getDocument(path);
|
|
const newDoc = transformDocument(content, updater);
|
|
await createDocument(path, newDoc);
|
|
}
|
|
|
|
async function readAll() {
|
|
const allDocuments = await getDocuments();
|
|
return Promise.all(
|
|
allDocuments.filter((d) => {
|
|
return d.name.startsWith(prefix) &&
|
|
d.contentType === "text/markdown" &&
|
|
!d.name.endsWith("index.md");
|
|
}).map((doc) => {
|
|
const id = doc.name.replace(prefix, "").replace(/\.md$/, "");
|
|
return read(id);
|
|
}),
|
|
);
|
|
}
|
|
|
|
return {
|
|
read,
|
|
readAll,
|
|
create,
|
|
update,
|
|
};
|
|
}
|