spb/server.js

1import express from "express"; 2import morgan from "morgan"; 3 4import { nanoid } from "nanoid"; 5 6import multer from "multer"; 7const upload = multer(); 8 9import config from "./config.js"; 10import db from "./db.js"; 11 12const app = express(); 13 14app.use((req, res, next) => { 15 res.set("Content-Type", "text/plain"); 16 next(); 17}); 18 19// enable logging 20app.use(morgan("short")); 21 22// routes - start 23app.get("/", (req, res) => { 24 const html = ` 25 spb(1) SPB spb(1) 26 27 NAME 28 spb: [s]imple [p]aste[b]in. 29 30 SYNOPSIS 31 <command> | curl -F 'spb=<-' ${config.host} 32 33 DESCRIPTION 34 As of now, spb only accepts text (as a pastebin should) 35 and the payload should be send a multipart-formdata. 36 Inspiration from https://github.com/rupa/sprunge. 37 38 EXAMPLES 39 ~$ cat ~/tmp/foo.txt | curl -F 'spb=<-' ${config.host} 40 ${config.host}/f85c64 41 ~$ firefox ${config.host}/f85c64 42 43 SEE ALSO 44 https://github.com/aktsbot/spb 45 `; 46 47 return res.status(200).send(html); 48}); 49 50app.post("/", upload.none(), async (req, res) => { 51 try { 52 if (!req.body.spb) { 53 return res.status(400).send("bad data\n"); 54 } 55 56 let gid = nanoid(6); 57 58 let n_paste = { 59 id_gen: gid, 60 content: req.body.spb, 61 }; 62 63 db.run( 64 `INSERT INTO pastes (id_gen, content) VALUES (@id_gen, @content)`, 65 n_paste 66 ); 67 68 return res.status(200).send(`${config.host}/${gid}\n`); 69 } catch (e) { 70 return res.status(500).send("save met unexpected errors\n"); 71 } 72}); 73 74app.get("/:gid", async (req, res) => { 75 try { 76 if (req.params.gid && req.params.gid.length < 6) { 77 return res.status(400).send("bad data\n"); 78 } 79 80 const p_find = db.query( 81 `SELECT content from pastes WHERE id_gen=@id_gen LIMIT 1`, 82 { 83 id_gen: req.params.gid, 84 } 85 ); 86 87 if (p_find.length === 0) { 88 return res.status(404).send("not found\n"); 89 } 90 91 return res.status(200).send(`${p_find[0]["content"]}`); 92 } catch (e) { 93 return res.status(500).send("fetch met unexpected errors\n"); 94 } 95}); 96// routes - end 97 98app.listen(config.port, () => { 99 console.log(`[spb] app listening on port ${config.port}`); 100});