Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
164 lines (151 loc) · 4.83 KB
/
Copy pathapp.js
File metadata and controls
164 lines (151 loc) · 4.83 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import http from 'http';
import https from 'https';
import path from 'path';
import express from 'express';
import hbs from 'hbs';
import moment from 'moment';
import bodyParser from 'body-parser';
import db from './db/models/index.js';
import logger, { getLogChild } from './helpers/logger.js';
import getClientConfig from './helpers/getClientConfig.js';
import { getEnv } from './helpers/common.js';
import { getDirnameByUrl, outputReq, outputRes } from './helpers/common.js';
import genRoutes from './routes/index.js';
import apiRoutes from './routes/api.js';
// config server
http.globalAgent.maxSockets = 100;
https.globalAgent.maxSockets = 100;
// some var
const baseDir = getDirnameByUrl(import.meta.url);
// database cleanup task
// removes actions and completed requests older than 60 days
const { Sequelize } = db;
const { Op } = Sequelize;
const cleanIntervalTime = 60 * 60 * 1000;
async function cleanupDb() {
const expiry = getEnv('DATABASE_EXPIRY')
? parseInt(getEnv('DATABASE_EXPIRY'))
: 60;
const numActions = await db.actions.destroy({
where: {
created_at: { [Op.lt]: moment().subtract(expiry, 'days').toDate() },
},
});
if (numActions > 0) {
logger.info('removed %d old actions', numActions);
}
const numUsers = await db.users.destroy({
where: {
updated_at: { [Op.lt]: moment().subtract(expiry, 'days').toDate() },
},
});
if (numUsers > 0) {
logger.info('removed %d old users', numUsers);
}
}
setInterval(() => {
logger.debug('running db cleanup');
cleanupDb().catch((error) => {
logger.error(error, 'error cleaning database');
});
}, cleanIntervalTime);
// load client config
const clientConfig = getClientConfig();
const clientConfigObject = JSON.parse(clientConfig);
// init server framework
const app = express();
// when is in dev environment
// start webpackMiddleware
if (getEnv('NODE_ENV') !== 'production') {
logger.info('Running in development mode');
// Use dynamic import to avoid loading webpack in production
import('./webpack/webpack.js').then((webpackModule) => {
webpackModule.default(app);
}).catch((error) => {
logger.error(error, 'Failed to load webpack middleware');
});
}
// logging middleware
app.use((req, res, next) => {
const start = process.hrtime();
const reqId =
req.headers['x-amzn-trace-id'] ||
req.headers['x-request-id'] ||
`dev-${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}`;
const reqIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
req.log = getLogChild({ req_id: reqId, ip: reqIp });
req.log.debug(outputReq(req), '<-- request');
res.set('X-Request-Id', reqId);
const logOut = () => {
const delta = process.hrtime(start);
const info = {
ms: delta[0] * 1e3 + delta[1] / 1e6,
code: res.statusCode,
};
req.log.info(info, '%s %s', req.method, req.url);
req.log.debug(outputRes(res), '--> response');
};
res.once('finish', logOut);
res.once('close', logOut);
next();
});
// set hbs viewer
hbs.registerHelper('endsWith', (str, suffix) => {
return str.endsWith(suffix);
});
hbs.registerHelper('clientConfig', () => clientConfig);
hbs.registerHelper('baseCss', () => new hbs.SafeString(
getEnv('NODE_ENV') !== 'production'
? ''
: '<link rel="stylesheet" href="/css/base.css" type="text/css" media="all"/>'
)
);
hbs.registerHelper('captchaJs', () => new hbs.SafeString(
getEnv('TURNSTILE_SWITCH') !== 'OFF'
? '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>'
: ''
)
);
hbs.registerHelper('gaCode', () => {
let gaCode = '';
if (clientConfigObject) {
gaCode = `<script async src="https://www.googletagmanager.com/gtag/js?id=${clientConfigObject.GOOGLE_ANALYTICS_ID}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${clientConfigObject.GOOGLE_ANALYTICS_ID}');
</script>`;
}
return new hbs.SafeString(gaCode);
});
hbs.registerPartials(`${baseDir}/views/partials`);
app.set('views', path.join(baseDir, 'views'));
app.set('view engine', 'hbs');
// other settings
app.enable('trust proxy');
app.disable('x-powered-by');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(baseDir, 'public')));
// set route
app.use('/', genRoutes({
baseDir,
}));
app.use('/api', apiRoutes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// further error handler
app.use((err, req, res) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : err;
// render the error page
res.status(err.status || 500);
res.json(err);
});
export default app;