Advertisement
xymz

Untitled

Nov 18th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // server.js
  2. // where your node app starts
  3.  
  4. // init project
  5. const express = require("express");
  6. const bodyParser = require("body-parser");
  7. const app = express();
  8. const fs = require("fs");
  9. app.use(bodyParser.urlencoded({ extended: true }));
  10. app.use(bodyParser.json());
  11.  
  12. // we've started you off with Express,
  13. // but feel free to use whatever libs or frameworks you'd like through `package.json`.
  14.  
  15. // http://expressjs.com/en/starter/static-files.html
  16. app.use(express.static("public"));
  17.  
  18. // init sqlite db
  19. const dbFile = "./.data/sqlite.db";
  20. const exists = fs.existsSync(dbFile);
  21. const sqlite3 = require("sqlite3").verbose();
  22. const db = new sqlite3.Database(dbFile);
  23.  
  24. // if ./.data/sqlite.db does not exist, create it, otherwise print records to console
  25. db.serialize(() => {
  26.   if (!exists) {
  27.     db.run(
  28.       "CREATE TABLE Dreams (id INTEGER PRIMARY KEY AUTOINCREMENT, dream TEXT)"
  29.     );
  30.     console.log("New table Dreams created!");
  31.  
  32.     // insert default dreams
  33.     db.serialize(() => {
  34.       db.run(
  35.         'INSERT INTO Dreams (dream) VALUES ("Find and count some sheep"), ("Climb a really tall mountain"), ("Wash the dishes")'
  36.       );
  37.     });
  38.   } else {
  39.     console.log('Database "Dreams" ready to go!');
  40.     db.each("SELECT * from Dreams", (err, row) => {
  41.       if (row) {
  42.         console.log(`record: ${row.dream}`);
  43.       }
  44.     });
  45.   }
  46. });
  47.  
  48. // http://expressjs.com/en/starter/basic-routing.html
  49. app.get("/", (request, response) => {
  50.   response.sendFile(`${__dirname}/views/index.html`);
  51. });
  52.  
  53. // endpoint to get all the dreams in the database
  54. app.get("/getDreams", (request, response) => {
  55.   db.all("SELECT * from Dreams", (err, rows) => {
  56.     response.send(JSON.stringify(rows));
  57.   });
  58. });
  59.  
  60. // endpoint to add a dream to the database
  61. app.post("/addDream", (request, response) => {
  62.   console.log(`add to dreams ${request.body}`);
  63.  
  64.   // DISALLOW_WRITE is an ENV variable that gets reset for new projects so you can write to the database
  65.   if (!process.env.DISALLOW_WRITE) {
  66.     const cleansedDream = cleanseString(request.body.dream);
  67.     db.run(`INSERT INTO Dreams (dream) VALUES (?)`, cleansedDream, error => {
  68.       if (error) {
  69.         response.send({ message: "error!" });
  70.       } else {
  71.         response.send({ message: "success" });
  72.       }
  73.     });
  74.   }
  75. });
  76.  
  77. // endpoint to clear dreams from the database
  78. app.get("/clearDreams", (request, response) => {
  79.   // DISALLOW_WRITE is an ENV variable that gets reset for new projects so you can write to the database
  80.   if (!process.env.DISALLOW_WRITE) {
  81.     db.each(
  82.       "SELECT * from Dreams",
  83.       (err, row) => {
  84.         console.log("row", row);
  85.         db.run(`DELETE FROM Dreams WHERE ID=?`, row.id, error => {
  86.           if (row) {
  87.             console.log(`deleted row ${row.id}`);
  88.           }
  89.         });
  90.       },
  91.       err => {
  92.         if (err) {
  93.           response.send({ message: "error!" });
  94.         } else {
  95.           response.send({ message: "success" });
  96.         }
  97.       }
  98.     );
  99.   }
  100. });
  101.  
  102. // helper function that prevents html/css/script malice
  103. const cleanseString = function(string) {
  104.   return string.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  105. };
  106.  
  107. // listen for requests :)
  108. var listener = app.listen(process.env.PORT, () => {
  109.   console.log(`Your app is listening on port ${listener.address().port}`);
  110. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement