Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
98 lines (77 loc) · 2.43 KB
/
Copy pathapp.js
File metadata and controls
98 lines (77 loc) · 2.43 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
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const { Database } = require('better-sqlite3');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
const dbPath = process.env.DB_PATH;
// Connect to the SQLite3 database using better-sqlite3
const db = require('better-sqlite3')(dbPath);
db.pragma('journal_mode = WAL');
const setupA = db.prepare(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT NOT NULL); `);
const setupB = db.prepare(`CREATE TABLE IF NOT EXISTS meetings (
id INT AUTO_INCREMENT PRIMARY KEY,
date DATE NOT NULL,
meeting_code VARCHAR(255) NOT NULL UNIQUE
);`)
const setupC = db.prepare(`CREATE TABLE IF NOT EXISTS player_meetings (
player_id INT,
meeting_id INT,
score INT NOT NULL,
FOREIGN KEY (player_id) REFERENCES users(id),
FOREIGN KEY (meeting_id) REFERENCES meetings(id)
);`);
try {
setupA.run();
setupB.run();
setupC.run();
console.log('success creating db');
} catch {
console.log('error creating database. Check db file exists and is able to be connected to.');
}
// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', (req, res) => {
res.render('index');
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/count', (req, res) => {
res.render('count');
});
app.get('/success', (req, res) => {
res.render('success');
});
app.get('/account', (req, res) => {
res.render('account');
});
app.post('/signup', (req, res) => {
const { name, email } = req.body;
// Insert the user data into the SQLite3 database (${name}, ${email})
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
try {
insert.run(name, email);
res.redirect('/success');
} catch (error) {
// Handle the error
console.error(error.message);
res.status(500).render('error', { error: error.stack })
}
});
app.use((req, res, next) => {
res.status(404).render('error', { error: 'Page not found' });
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).render('error', { error: 'Internal server error' });
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});