generated from samchon/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
68 lines (58 loc) · 2.01 KB
/
server.ts
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
import fs from "fs";
import { randint } from "tstl/algorithm/random";
import { Singleton } from "tstl/thread/Singleton";
import { MyBackend } from "../MyBackend";
import { MyGlobal } from "../MyGlobal";
import { Scheduler } from "../schedulers/Scheduler";
import { ErrorUtil } from "../utils/ErrorUtil";
const EXTENSION = __filename.substr(-2);
if (EXTENSION === "js") require("source-map-support/register");
const directory = new Singleton(async () => {
await mkdir(`${__dirname}/../../assets`);
await mkdir(`${__dirname}/../../assets/logs`);
await mkdir(`${__dirname}/../../assets/logs/errors`);
});
function cipher(val: number): string {
if (val < 10) return "0" + val;
else return String(val);
}
async function mkdir(path: string): Promise<void> {
try {
await fs.promises.mkdir(path);
} catch {}
}
async function handle_error(exp: any): Promise<void> {
try {
const date: Date = new Date();
const fileName: string = `${date.getFullYear()}${cipher(
date.getMonth() + 1,
)}${cipher(date.getDate())}${cipher(date.getHours())}${cipher(
date.getMinutes(),
)}${cipher(date.getSeconds())}.${randint(0, Number.MAX_SAFE_INTEGER)}`;
const content: string = JSON.stringify(ErrorUtil.toJSON(exp), null, 4);
await directory.get();
await fs.promises.writeFile(
`${__dirname}/../../assets/logs/errors/${fileName}.log`,
content,
"utf8",
);
} catch {}
}
async function main(): Promise<void> {
// BACKEND SEVER LATER
const backend: MyBackend = new MyBackend();
await backend.open();
//----
// POST-PROCESSES
//----
// UNEXPECTED ERRORS
global.process.on("uncaughtException", handle_error);
global.process.on("unhandledRejection", handle_error);
// SCHEDULER ONLY WHEN MASTER
if (MyGlobal.env.MODE !== "real" || process.argv[3] === "master")
await Scheduler.repeat();
}
main().catch((exp) => {
console.log(exp);
process.exit(-1);
});