-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
192 lines (149 loc) · 5.02 KB
/
app.js
File metadata and controls
192 lines (149 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Import the express module
import express from "express";
import mysql2 from 'mysql2';
import dotenv from 'dotenv';
import {validateForm} from './validation.js';
// Define a port number where server will listen
const PORT = 3009;
dotenv.config();
// Create an express application
const app = express();
const pool = mysql2.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT
}).promise();
app.get('/db-test', async (req, res) => {
try {
const poems = await pool.query('SELECT * FROM poems');
res.send(poems[0]);
} catch (err) {
console.error('Database error:', err);
res.status(500).send('Database error: ' + err.message);
}
});
// Enable static file serving
app.use(express.static("public"));
// Set view engine to EJS
app.set("view engine", "ejs");
// "Middleware" allows express to read form data and store it in req.body
app.use(express.urlencoded({ extended: true }));
const poems = [];
// Define our main route ('/')
// Default route
app.get("/", async(req, res) => {
try {
// Read all poems from db
// newest first
let sql = 'SELECT * FROM poems ORDER BY timestamp DESC';
const poems = await pool.query(sql);
res.render('home', { poems : poems[0] });
} catch (err) {
console.error('Database error:', err);
res.status(500).send('Error loading orders: ' + err.message);
}
});
// Form route
app.get("/submit-poem", (req, res) => {
res.render("form");
});
// Poem submission route
app.post("/submit-poem", async (req, res) => {
try {
// Get form data from req.body
const poem = req.body;
// Calling validation.js to validate our form
const valid = validateForm(poem);
// If there are errors, it will not submit
if (!valid.isValid) {
console.log(valid);
res.render('form', {errors: valid.errors});
return;
}
if (poem.tags.trim() == "") {
poem.tags = "none";
}
// Log the order data (for debugging)
console.log('New poem submitted:', poem);
// Set poem date to null if empty string
if (poem.date == "") {
poem.date = null;
}
// SQL INSERT query with placeholders to prevent SQL injection
const sql = `INSERT INTO poems(author, title, tags, date, poem)
VALUES (?, ?, ?, ?, ?);`;
console.log(poem.tags);
// Parameters array must match the order of ? placeholders
// Make sure your property names match your order names
const params = [
poem.author,
poem.title,
poem.tags,
poem.date,
poem.poem
];
// Execute the query and grab the primary key of the new row
const result = await pool.execute(sql, params);
console.log('Order saved with ID:', result[0].insertId);
console.log(params);
// Add timestamp for confirmation page
poem.timestamp = new Date();
console.log(poem.timestamp);
// Render confirmation page with the adoption data
res.render('confirmation', { poem });
} catch (err) {
console.error('Error saving poem:', err);
res.status(500).send('Sorry, there was an error posting your poem. Please try again.');
}
});
// Delete-poem route
app.post('/delete-poem/:id', async (req, res) => {
try {
const sql = 'DELETE FROM poems WHERE id = ?';
const params = [req.params.id];
await pool.execute(sql, params);
res.redirect('/');
} catch (err) {
console.error('Error deleting poem:', err);
res.status(500).send('Sorry, there was an error deleting the poem. Please try again!');
}
})
/*
app.post("/submit-poem", (req, res) => {
const rawTags = req.body.tags ?? "";
const tagsString = Array.isArray(rawTags) ? rawTags.join(",") :
String(rawTags);
const tags = tagsString
.split(",")
.map(t => t.trim())
.filter(Boolean);
const poem = {
author: req.body.author,
title: req.body.title,
tags,
date: req.body.date,
poem_body: req.body.poem,
timestamp: new Date()
};
poems.push(poem);
res.render("confirmation", { poem });
});
*/
// Admin route
app.get('/admin', async (req, res) => {
try {
// Fetch all orders from database, newest first
const [poems] = await pool.query('SELECT * FROM poems ORDER BY timestamp DESC');
// Render the admin page
res.render('admin', { poems });
} catch (err) {
console.error('Database error:', err);
res.status(500).send('Error loading orders: ' + err.message);
}
});
// Start server and listen on designated port
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});