-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
84 lines (72 loc) · 2.1 KB
/
Copy pathserver.js
File metadata and controls
84 lines (72 loc) · 2.1 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
require('dotenv').config();
const path = require('path');
const express = require('express');
const { pool, initDb } = require('./db');
const app = express();
const PORT = process.env.PORT || 3000;
// View engine + middleware
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// Homepage: list all saved notes, newest first.
app.get('/', async (req, res, next) => {
try {
const [notes] = await pool.query(
'SELECT id, title, body, created_at FROM notes ORDER BY created_at DESC, id DESC'
);
res.render('index', { notes });
} catch (err) {
next(err);
}
});
// Form to create a new note.
app.get('/notes/new', (req, res) => {
res.render('new');
});
// Create a note.
app.post('/notes', async (req, res, next) => {
try {
const title = (req.body.title || '').trim();
const body = (req.body.body || '').trim();
if (!title || !body) {
return res.status(400).render('new', {
error: 'Both a title and a body are required.',
values: { title, body },
});
}
await pool.query('INSERT INTO notes (title, body) VALUES (?, ?)', [title, body]);
res.redirect('/');
} catch (err) {
next(err);
}
});
// Health check route.
app.get('/health', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({ status: 'ok', database: 'connected', uptime: process.uptime() });
} catch (err) {
res.status(503).json({ status: 'error', database: 'disconnected' });
}
});
// 404 handler
app.use((req, res) => {
res.status(404).render('error', { message: 'Page not found.' });
});
// Error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(500).render('error', { message: 'Something went wrong.' });
});
// Initialize the database, then start the server.
initDb()
.then(() => {
app.listen(PORT, () => {
console.log(`NoteTaker app listening on port ${PORT}`);
});
})
.catch((err) => {
console.error('Failed to initialize database:', err);
process.exit(1);
});