-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo.min.js
1 lines (1 loc) · 2.14 KB
/
demo.min.js
1
'use strict'; const path = require("path"), util = require("util"), fs = require("fs"), readFile = util.promisify(fs.readFile), writeFile = util.promisify(fs.writeFile), readDir = util.promisify(fs.readdir), express = require("express"), cors = require("cors"), bodyParser = require("body-parser"), logger = require("./middleware/logger"), PORT = process.env.PORT || 5e3, DATA_DIR = "data", TAG_RE = /#\w+/g, slugToPath = a => { return path.join(DATA_DIR, `${a}.md`) }, app = express(); app.use(cors()), app.use(logger), app.use(bodyParser.json()), app.use("/", express.static(path.join(__dirname, "client", "build"))), app.get("/api/page/:slug", async (a, b) => { const c = slugToPath(a.params.slug); try { const a = await readFile(c, "utf-8"); b.json({ status: "ok", body: a }) } catch (a) { b.json({ status: "error", message: "Page does not exist." }) } }), app.post("/api/page/:slug", async (a, b) => { const c = slugToPath(a.params.slug); try { const d = a.body.body; await writeFile(c, d), b.json({ status: "ok" }) } catch (a) { b.json({ status: "error", message: "could not write page." }) } }), app.get("/api/pages/all", async (a, b) => { const c = await readDir(DATA_DIR), d = c.map(a => path.parse(a).name); b.json({ status: "ok", pages: d }) }), app.get("/api/tags/all", async (a, b) => { let c = await readDir(DATA_DIR); c = c.map(a => path.join(DATA_DIR, a)); const d = new Set, e = c.map(async a => { const b = await readFile(a, "utf-8"), c = b.match(TAG_RE); c && c.forEach(a => d.add(a.substring(1))) }); await Promise.all(e), b.json({ status: "ok", tags: Array.from(d) }) }), app.get("/api/tags/:tag", async (a, b) => { const c = a.params.tag; let d = await readDir(DATA_DIR); d = d.map(a => path.join(DATA_DIR, a)); const e = d.map(async a => { const b = await readFile(a, "utf-8"), d = b.match(TAG_RE); if (d && d.includes(`#${c}`)) return path.parse(a).name }), f = await Promise.all(e), g = f.filter(a => a); b.json({ status: "ok", tag: c, pages: g }) }), app.get("*", (a, b) => { b.sendFile(path.join(__dirname, "client", "build", "index.html")) }), app.listen(PORT, a => a ? void console.error(a) : void console.log(`Wiki app is serving at http://localhost:${PORT}`));