forked from AI-Global/design-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (82 loc) · 2.49 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
const { SystemUpdate } = require('@material-ui/icons');
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const app = express();
const port = process.env.PORT || 5000;
require('dotenv').config();
// Force HTTPS
app.use((req, res, next) => {
if (
process.env.NODE_ENV == 'production' &&
req.headers['x-forwarded-proto'] != 'https'
) {
return res.redirect('https://' + req.headers.host + req.url);
}
next();
});
// Serve static assets from backend
app.use((req, res, next) => {
if (
!req.originalUrl.startsWith('/api/') &&
[
'js',
'json',
'css',
'png',
'map',
'ico',
'txt',
'jpg',
'woff2',
'woff',
'ttf',
].filter((ext) => req.originalUrl.endsWith('.' + ext)).length == 0
) {
// Serve index html
return res.sendFile(path.join(__dirname, 'build', 'index.html'));
}
// Serve API or static build files
next();
});
// CORS
app.use((req, res, next) => {
let fetchOrigin = req.headers.origin;
// TODO: validate fetchOrigin
res.header('Access-Control-Allow-Origin', fetchOrigin);
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, X-Auth-Token, Content-Type, Accept, Authorization'
);
next();
});
app.use('/', express.static(path.join(__dirname, 'build')));
app.use(express.json());
app.use('/api/questions', require('./api/routes/questions'));
app.use('/api/responses', require('./api/routes/responses'));
app.use('/api/trustedAIProviders', require('./api/routes/trustedAIProviders'));
app.use('/api/trustedAIResources', require('./api/routes/trustedAIResources'));
app.use('/api/users', require('./api/routes/users'));
app.use('/api/submissions', require('./api/routes/submissions'));
app.use('/api/metadata', require('./api/routes/metadata'));
app.use('/api/dimensions', require('./api/routes/dimensions'));
app.use('/api/analytics', require('./api/routes/analytics'));
app.use('/api/subdimensions', require('./api/routes/subdimensions'));
let runServer = () => {
mongoose.connection
.on('error', console.warn)
.on('disconnected', console.warn)
.once('open', () => {
console.log(`Serving http://:${port}`);
app.listen(port);
});
return mongoose.connect(process.env.MONGODB_URL, {
keepAlive: 1,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
autoReconnect: true,
});
};
runServer();