import {readdir as rd, readFile as rf, writeFile as wf} from "node:fs/promises"; import {sj, res204, err400, err500} from "./utils.js"; import {authed} from "./auth.js"; import {NOTE_DIR} from "./config.js"; function genNoteID() { const now = new Date().toISOString(); return now.replace(/[^0-9]/g,"").slice(0,16); } async function newNote(req, res) { const noteID = genNoteID(); const noteFile = `${NOTE_DIR}/${req.uid}/${noteID}.md`; console.log(Date.now()+` Creating note ${req.uid}:${noteID}`); await wf(noteFile, ""); sj(res, {id:noteID, content:""}); } async function getNote(req, res, match) { console.log(Date.now()+` Getting note ${req.uid}:${match.noteID}`); const noteFile = `${NOTE_DIR}/${req.uid}/${match.noteID}.md`; const content = await rf(noteFile, "utf8"); sj(res, {id:match.noteID, content}); } async function setNote(req, res, match, data) { console.log(Date.now()+` Setting note ${req.uid}:${match.noteID}`); if (match.noteID !== data.id) return err400(res); const noteFile = `${NOTE_DIR}/${req.uid}/${match.noteID}.md`; await wf(noteFile, data.content, "utf8"); sj(res, {}); } async function listNotes(req, res) { console.log(Date.now()+` Getting notes for ${req.uid}`); const files = await rd(`${NOTE_DIR}/${req.uid}`); const notes = files.map(fn => fn.slice(0,-3)); sj(res, notes); } // TODO list in order of recent updates w/ timestamps // TODO pagination? Bulk get? // TODO handle fs errors export const attach = app => { app.get("/list", authed(listNotes)); app.post("/new", authed(newNote)); app.get("/(?[0-9]{16})", authed(getNote)); app.jpost("/(?[0-9]{16})", authed(setNote)); };