-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
94 lines (79 loc) · 1.85 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const bodyParser = require('body-parser');
const express = require('express');
const morgan = require('morgan');
const nunjucks = require('nunjucks');
const db = require('./database');
const { idRegex, nanoid } = require('./id');
const app = express();
app.use(morgan('dev'));
app.use(express.static('public'));
nunjucks.configure('views', {
autoescape: true,
express: app,
});
const urlencodedParser = bodyParser.urlencoded({ extended: false });
/**
* GET /
*/
app.get('/', async (request, response) => {
response.render('index.html');
});
/**
* POST /
*/
app.post('/', urlencodedParser, async (request, response) => {
const { note } = request.body;
if (!note) {
response.render('index.html');
return;
}
// ensure note id is unique
let noteId;
while (true) {
noteId = nanoid();
if (!(await db.get(noteId))) {
await db.set(noteId, note);
break;
}
}
const noteUrl = `${request.get('host')}/${noteId}`;
response.render('index.html', { noteId, noteUrl });
});
/**
* GET /:id
*/
app.get('/:id', async (request, response, next) => {
const noteId = request.params.id;
if (!idRegex.test(noteId)) {
return next();
}
const note = await db.get(noteId);
if (!note) {
return next();
}
await db.delete(noteId);
response.render('index.html', { note });
});
/**
* GET /empty-database
*/
if (process.env.NODE_ENV === 'development') {
app.get('/empty-database', async (request, response, next) => {
await db.empty();
response.render('index.html', { message: 'Emptied Database' });
});
}
/**
* 404
*/
app.use((request, response) => {
response.status(404).render('index.html', { message: 'Not Found' });
});
/**
* Error
*/
app.use((error, request, response, next) => {
next(error);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('Listening on port %d', port));