-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (71 loc) · 2.21 KB
/
index.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
// todo: 黑白名单改为redis缓存
// require("./config/projects-blacklist");
require("./config/dotenv");
require("./redis");
const https = require("https");
const { readdir, readFile } = require("fs").promises;
const jwt = require("koa-jwt");
const Koa = require("koa");
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");
const { protectedRouter, unprotectedRouter } = require("./router");
const { logHandle, errLogger } = require("./middleware/log4js");
const catchException = require("./middleware/catch_exception");
const { JWT_SECRET } = require("./config/constants");
const app = new Koa();
app.use(logHandle());
app.use(cors());
app.use(bodyParser({ enableTypes: ["json", "text", "form"] }));
app.use(catchException());
app.use(unprotectedRouter.routes()).use(unprotectedRouter.allowedMethods());
app.use(jwt({ secret: JWT_SECRET }));
app.use(protectedRouter.routes()).use(protectedRouter.allowedMethods());
app.on("error", (err, ctx) => {
errLogger(ctx, err);
});
(async () => {
try {
const files = await readdir(__dirname + "/ssl");
let certFileName = null;
let keyFileName = null;
for (const fname of files) {
if (fname.includes(".key")) {
keyFileName = fname;
} else if (fname.includes(".crt") || fname.includes(".cer")) {
certFileName = fname;
}
}
if (certFileName && keyFileName) {
httpsListen(certFileName, keyFileName);
} else {
httpListen();
}
} catch (error) {
httpListen();
console.log("err::", error);
}
})();
function httpListen() {
app.listen(process.env.NODESERVER_PORT || 8233, function () {
console.log(
`http service is running here: http://127.0.0.1:${
process.env.NODESERVER_PORT || 8233
}`
);
});
}
async function httpsListen(certFileName, keyFileName) {
const sslOptions = {
cert: await readFile(__dirname + "/ssl/" + certFileName),
key: await readFile(__dirname + "/ssl/" + keyFileName),
};
https
.createServer(sslOptions, app.callback())
.listen(process.env.NODESERVER_PORT || 8233, () => {
console.log(
`https service is running here: http://127.0.0.1:${
process.env.NODESERVER_PORT || 8233
}`
);
});
}