· 5 years ago · Feb 23, 2020, 11:54 AM
1// server.js
2// where your node app starts
3
4// init project
5const express = require("express");
6const bodyParser = require("body-parser");
7const app = express();
8const fs = require("fs");
9app.use(bodyParser.urlencoded({ extended: true }));
10app.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
16app.use(express.static("public"));
17
18// init sqlite db
19const dbFile = "./.data/sqlite.db";
20const exists = fs.existsSync(dbFile);
21const sqlite3 = require("sqlite3").verbose();
22const db = new sqlite3.Database(dbFile);
23
24// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
25db.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
49app.get("/", (request, response) => {
50 response.sendFile(`${__dirname}/views/index.html`);
51});
52
53// endpoint to get all the dreams in the database
54app.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
61app.post("/addDream", (request, response) => {
62 console.log(`add to dreams ${request.body.dream}`);
63
64 // DISALLOW_WRITE is an ENV variable that gets reset for new projects
65 // so they can write to the database
66 if (!process.env.DISALLOW_WRITE) {
67 const cleansedDream = cleanseString(request.body.dream);
68 db.run(`INSERT INTO Dreams (dream) VALUES (?)`, cleansedDream, error => {
69 if (error) {
70 response.send({ message: "error!" });
71 } else {
72 response.send({ message: "success" });
73 }
74 });
75 }
76});
77
78// endpoint to clear dreams from the database
79app.get("/clearDreams", (request, response) => {
80 // DISALLOW_WRITE is an ENV variable that gets reset for new projects so you can write to the database
81 if (!process.env.DISALLOW_WRITE) {
82 db.each(
83 "SELECT * from Dreams",
84 (err, row) => {
85 console.log("row", row);
86 db.run(`DELETE FROM Dreams WHERE ID=?`, row.id, error => {
87 if (row) {
88 console.log(`deleted row ${row.id}`);
89 }
90 });
91 },
92 err => {
93 if (err) {
94 response.send({ message: "error!" });
95 } else {
96 response.send({ message: "success" });
97 }
98 }
99 );
100 }
101});
102
103// helper function that prevents html/css/script malice
104const cleanseString = function(string) {
105 return string.replace(/</g, "<").replace(/>/g, ">");
106};
107
108// listen for requests :)
109var listener = app.listen(process.env.PORT, () => {
110 console.log(`Your app is listening on port ${listener.address().port}`);
111});