-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
80 lines (69 loc) · 3.42 KB
/
app.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
// _____ _ _ _ _ ____ ___
// |_ _| __ __ ___ _____| | (_)_ __ __ _ ___ / \ | _ \_ _|
// | || '__/ _` \ \ / / _ \ | | | '_ \ / _` / __|_____ / _ \ | |_) | |
// | || | | (_| |\ V / __/ | | | | | | (_| \__ \_____/ ___ \| __/| |
// |_||_| \__,_| \_/ \___|_|_|_|_| |_|\__, |___/ /_/ \_\_| |___|
// |___/
//
// By BLxcwg666 <[email protected]>
const express = require('express');
const cluster = require('cluster');
const config = require('./config');
const log = require('./modules/logger');
const moment = require('moment-timezone');
const routes = require('./modules/router');
const sql = require('./modules/sqlConfig');
const compression = require('compression');
const numCPUs = require('os').cpus().length;
const cookieParser = require('cookie-parser');
const redisClient = require('./modules/redisClient');
const host = config.API_HOST;
const port = config.API_PORT;
global.version = "5.5.3";
global.time = function () {
return moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
}
if (cluster.isPrimary) {
console.log(" _____ _ _ _ _ ____ ___ \n |_ _| __ __ ___ _____| | (_)_ __ __ _ ___ / \\ | _ \\_ _|\n | || '__/ _` \\ \\ / / _ \\ | | | '_ \\ / _` / __|_____ / _ \\ | |_) | | \n | || | | (_| |\\ V / __/ | | | | | | (_| \\__ \\_____/ ___ \\| __/| | \n |_||_| \\__,_| \\_/ \\___|_|_|_|_| |_|\\__, |___/ /_/ \\_\\_| |___|\n |___/");
console.log(`\nCopyright © 2020-2025 Travellings Project. All rights reserved.(v${global.version})\n`);
// 主进程中检查数据库
log.info("尝试连接到数据库...", "APP")
sql.sync()
.then(() => {
log.ok("成功连接到数据库~", "APP")
// 复制线程
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// 启动 API
const app = express();
app.use(compression());
app.use(express.json());
app.use(cookieParser());
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && origin.match(/^https?:\/\/([a-zA-Z0-9-]+\.)*travellings\.cn$/)) {
res.header('Access-Control-Allow-Origin', origin);
}
res.header('Cache-Control', 'no-store');
res.header('X-Powered-By', 'Travellings Project');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.use(function (req, res, next) { // 把 redis 对象交给其他路由
req.redisClient = redisClient;
next();
});
app.use('/', routes);
app.listen(port, host, async () => {
log.info(`API Started at port ${port} on ${host}`, "APP")
});
})
.catch(err => log.err(err, "APP")); // 数据库同步 + 错误处理
cluster.on('exit', (worker, code, signal) => {
log.warn(`线程 PID ${worker.process.pid} 已退出,代码:${code}`, "APP")
log.info(`尝试启动新线程`, "APP")
cluster.fork(); // 重新启动子进程
});
}