This repository has been archived by the owner on Sep 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
77 lines (63 loc) · 1.58 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
const express = require('express');
const lowdb = require('lowdb');
const lodashId = require('lodash-id');
const cookieParser = require('cookie-parser');
const FileAsync = require('lowdb/adapters/FileAsync');
const { DB_PATH, DB_DEFAULTS } = require('./db');
const meetupRouter = require('./routes/meetup');
const userRouter = require('./routes/user');
const PORT = process.env.PORT || 3000;
let db;
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});
app.use(cookieParser());
app.use((req, res, next) => {
req.db = db;
next();
});
app.use((req, res, next) => {
const DELAY = process.env.DELAY;
if (!DELAY || DELAY === 'false') {
next();
return;
}
let delayInMs = parseInt(DELAY, 10);
if (isNaN(delayInMs)) {
next();
return;
}
delayInMs = Math.floor(Math.random() * delayInMs);
setTimeout(() => next(), delayInMs);
});
app.get('/', (req, res) => {
res.send({
status: 'Running'
});
});
app.use('/meetup', meetupRouter);
app.use('/user', userRouter);
app.all('*', (req, res) => {
res.status(404).send('Only unicorns here 🦄');
});
async function initDb() {
db = await lowdb(new FileAsync(DB_PATH));
db._.mixin(lodashId);
return db.defaults(DB_DEFAULTS).write();
}
async function run() {
await initDb();
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
}
run().catch(err => {
console.error(err);
process.exit(1);
});