-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
78 lines (64 loc) · 2.1 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
78
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const colors = require('colors');
const cookieParser = require('cookie-parser');
const cors = require('cors');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// Body parser
app.use(express.json({ extended: false }));
// Cookie parser
app.use(cookieParser());
// Cors
app.use(
cors({
origin: ['http://localhost:3000', 'https://reactpp.com', 'https://reactpinpoint.com'],
credentials: true,
})
);
// Dev logging middleware
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// Routing
const isAuthorized = require('./auth/auth');
const register = require('./auth/register');
const login = require('./auth/login');
const logout = require('./auth/logout');
const userRouter = require('./routes/user');
const projectRouter = require('./routes/project');
const commitRouter = require('./routes/commit');
app.use('/api/user', isAuthorized, userRouter);
app.use('/api/project', isAuthorized, projectRouter);
app.use('/api/commit', commitRouter);
app.get('/api/auth', isAuthorized, (req, res) => {
res.status(200).json({ success: true, user_id: res.locals.user_id });
});
app.post('/api/register', register, (req, res) => {
res.status(201).json({ success: true, newUser: res.locals.newUser });
});
app.post('/api/login', login, (req, res) => {
res.status(200).json({ success: true, loggedIn: res.locals.loggedIn });
});
app.get('/api/logout', logout, (req, res) => {
res.status(200).json({ success: true, loggedOut: res.locals.loggedOut });
});
app.get('/', isAuthorized, (req, res) => {
res.send('Welcome to reactpp API');
});
// Global error handler
app.use((err, req, res, next) => {
if (process.env.NODE_ENV === 'development') {
console.log(`Error stack -> ${JSON.stringify(err, null, 2)}`.red);
}
return res.status(err.statusCode || 500).json({
success: false,
error: err.message || 'Server Error',
});
});
// Run the server
app.listen(PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`.yellow.bold);
});