summaryrefslogtreecommitdiff
path: root/app/note-store.js
blob: 8ad54db137eeebdac506e146c816018bb6df596e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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("/(?<noteID>[0-9]{16})", authed(getNote));
  app.jpost("/(?<noteID>[0-9]{16})", authed(setNote));
};