-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (44 loc) · 1.27 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
const express = require('express');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const { JWT_SECRET = "notsosecret" } = process.env;
const { getUserById } = require("./db")
const server = express();
const morgan = require('morgan');
server.use(morgan('dev'));
const cors = require('cors');
server.use(cors());
server.use(express.json());
const path = require('path');
server.use(express.static(path.join(__dirname, 'build')));
server.use(async (req, res, next) => {
try {
const auth = req.header('Authorization');
if(!auth) {
next();
} else {
let [, token] = auth.split(' ');
token = token.trim();
const userObj = jwt.verify(token, JWT_SECRET);
req.user = await getUserById(userObj.id);
next();
}
} catch (error) {
next(error)
}
})
server.use('/api', require('./routes'));
server.use((req, res, next) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'))
});
const client = require('./db/client');
const PORT = process.env.PORT || 4000;
server.listen(PORT, async () => {
console.log(`Server is running on ${ PORT }!`);
try {
await client.connect();
console.log('Database is open for business!');
} catch (error) {
console.error("Database is closed for repairs!", error);
}
});