-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (45 loc) · 1.33 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
const environment = process.argv.slice(2).length ? process.argv.slice(2)[0] : 'db'
const port = process.argv.slice(3).length ? process.argv.slice(3)[0] : 3001
const fs = require('fs');
require('dotenv').config()
const secretKey = process.env.SECRET_KEY
const mode = environment === 'dev' ? fs.constants.COPYFILE_EXCL : null
fs.copyFile('db.json', `${environment}.json`, mode, (err) => {
if (err) {
if (err.code === 'EEXIST') {
console.log(`Using existing ${environment}.json file`);
return runServer()
} else {
throw err;
}
}
runServer()
});
function runServer() {
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router(`${environment}.json`);
const middlewares = jsonServer.defaults();
server.use(middlewares);
function isAuthorized(req) {
if (req.headers.authorization) {
const [type, credentials] = req.headers.authorization.split(' ')
if (type === 'Bearer' && credentials === secretKey) {
return true
}
}
if (req.query.user) {
return true
}
return false
}
server.use((req, res, next) => {
if (isAuthorized(req)) {
next()
} else {
res.sendStatus(401)
}
})
server.use(router);
server.listen(port, () => console.log(`Server ${environment} is running`));
}