-
Notifications
You must be signed in to change notification settings - Fork 83
/
server.js
146 lines (122 loc) · 3.5 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { graphqlHTTP } from 'express-graphql';
import http from 'http';
import jsonServer from 'json-server';
import { Low } from 'lowdb';
import { JSONFile } from 'lowdb/node';
import { Server } from 'socket.io';
import { createProxyMiddleware } from 'http-proxy-middleware';
import cors from 'cors';
import { CONFIG } from './config.js';
import { isAuthenticated } from './utils/jwt-authenticate.js';
import { schema, setupRootValue } from './src/graphql.js';
import {
loginHandler,
registerHandler,
refreshTokenHandler,
socketEmit,
testHandler,
uploadFileHandler,
uploadFilesHandler,
} from './src/rest.js';
import socketHandler from './src/socket-io.js';
const db = new Low(new JSONFile(CONFIG.databaseFile));
await db.read();
const app = jsonServer.create();
const router = jsonServer.router(CONFIG.databaseFile);
const middlewares = jsonServer.defaults();
const port = process.env.PORT || CONFIG.defaultPort;
const server = http.createServer(app);
// Init socket io server
const io = new Server(server, {
cors: { origin: '*' },
});
io.on('connection', (socket) => {
socketHandler(socket, io);
});
// Config proxy middlewares
if (CONFIG.proxyServer) {
app.use(
CONFIG.proxyUrl,
createProxyMiddleware({
target: CONFIG.proxyServer,
changeOrigin: true,
ws: true,
logger: console,
onProxyRes: function (proxyRes, req, res) {
cors()(req, res, () => {});
},
})
);
}
// Init graphql
app.use('/graphql', graphqlHTTP({ schema, rootValue: setupRootValue(db), graphiql: true }));
// Set default middlewares (logger, static, cors and no-cache)
app.use(middlewares);
// Handle POST, PUT and PATCH request
app.use(jsonServer.bodyParser);
// Save createdAt and updatedAt automatically
app.use((req, res, next) => {
const currentTime = Date.now();
if (req.method === 'POST') {
req.body.createdAt = currentTime;
req.body.modifiedAt = currentTime;
} else if (['PUT', 'PATCH'].includes(req.method)) {
req.body.modifiedAt = currentTime;
}
next();
});
// Test web socket request
app.post('/socket-emit', (req, res) => {
socketEmit(io, req, res);
});
// Test request (change the response in src/rest.js)
app.get('/test', (req, res) => {
testHandler(db, req, res);
});
// Register request
app.post('/register', (req, res) => {
registerHandler(db, req, res);
});
// Login request
app.post('/login', (req, res) => {
loginHandler(db, req, res);
});
// Renew Token request
app.post('/refresh-token', (req, res) => {
refreshTokenHandler(req, res);
});
// Upload 1 file
app.post('/upload-file', uploadFileHandler);
// Upload multiple files
app.post('/upload-files', uploadFilesHandler);
// Access control
app.use((req, res, next) => {
const protectedResources = db.data.protectedResources;
if (!protectedResources) {
next();
return;
}
const resource = req.path.slice(1).split('/')[0];
const protectedResource =
protectedResources[resource] && protectedResources[resource].map((item) => item.toUpperCase());
const reqMethod = req.method.toUpperCase();
if (protectedResource && protectedResource.includes(reqMethod)) {
if (isAuthenticated(req)) {
next();
} else {
res.sendStatus(401);
}
} else {
next();
}
});
// Rewrite routes
const urlRewriteFile = new JSONFile(CONFIG.urlRewriteFile);
const rewriteRules = await urlRewriteFile.read();
app.use(jsonServer.rewriter(rewriteRules));
// Setup others routes
app.use(router);
// Start server
server.listen(port, () => {
console.log('Server is running on port ' + port);
});