-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (54 loc) · 2.17 KB
/
server.js
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
import express from 'express';
import path from 'path';
import {db} from './model/db.js';
import ejs from 'ejs';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// import {steps} from './model/steps.js';
import {host, port} from './settings.js';
import bodyParser from 'body-parser';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
app.use(express.static('public'));
// set the view engine to ejs
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('layout', {
answerText: '<div><form action="/intro"><label for="name">To start the game please enter your name:</label><br><input type="text" id="name" name="name"><br><input type="submit" value="Submit"></form></div>'
})
})
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/intro', async (req, res) => {
let name = req.query.name;
if(name) {
let record = {
name: name
};
await db.collection('users').insertOne(record);
let dbRes = await db.collection("users").findOne({name:name});
res.render('layout', {
answerText: `Hello ${dbRes.name}! Today is a wonderful day! You and your sister are going to Paris to visit your relatives. You grab your bags and dump them in the boot of the Uber that is taking you to the airport. You clamber into the backseat with your sister and fall into a light sleep. You are quietly snoring when you hear the tyres skid to a stop. Something in your gut tells you that you are not safe anymore. To continue go to <a href=${host}/step/step1>step1</a>`
});
} else {
res.redirect('/')
}
})
app.get('/step/:stepId', async (req, res) => {
let stepId = req.params.stepId
let answer = req.query.answer;
let step = await db.collection('steps').findOne({name: stepId})
let answers = step ? step.answers : {};
console.log('step: ', step);
let answerText = answers._default;
if(answer) {
answerText = answers[answer];
}
console.log('answerText: ', answerText);
res.render('layout', {
answerText: ejs.render(answerText, {host: host})
});
})
app.listen(port, () => {
console.log(`App is listening at ${host}`)
});