poof/app/routes.js

1import { Router } from "express"; 2 3import db from "./db.js"; 4import config from "./config.js"; 5 6import { makePoofId, pageHtml } from "./utils.js"; 7 8const router = Router(); 9 10// home page where the user can create a poof message 11router.get("/", (req, res) => { 12 return res.send(pageHtml.home()); 13}); 14 15// after creating a poof, they see this page 16router.get("/done/:id", (req, res) => { 17 const fullUrl = 18 req.protocol + 19 "://" + 20 req.get("host") + 21 `${config.basePath}/p/${req.params.id}`; 22 return res.send(pageHtml.done({ fullUrl })); 23}); 24 25// the actual page where the user can see the poof 26router.get("/p/:id", (req, res) => { 27 let poof = ""; 28 let html = pageHtml.view({ poof: "", showWarning: true }); 29 if (req.query.view == 1) { 30 const result = db.get(`SELECT id, poof FROM poofs WHERE id = ?`, [ 31 req.params.id, 32 ]); 33 if (result && result.poof) { 34 poof = result.poof; 35 // delete after view 36 db.run(`DELETE FROM poofs where id = @id`, { id: req.params.id }); 37 } 38 html = pageHtml.view({ poof, showWarning: false }); 39 } 40 return res.send(html); 41}); 42 43// creating a poof 44router.post("/", (req, res, next) => { 45 if (!req.body.poof) { 46 let error = new Error("poof not provided"); 47 error.statusCode = 400; 48 throw error; 49 } 50 51 const poof = { 52 id: makePoofId(), 53 poof: req.body.poof, 54 }; 55 56 const result = db.run( 57 "INSERT INTO poofs (id, poof) VALUES (@id, @poof)", 58 poof, 59 ); 60 return res.redirect(`${config.basePath}/done/${poof.id}`); 61}); 62 63export default router;