-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (92 loc) · 2.8 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
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
"use strict";
require("make-promises-safe");
require("dotenv").config();
// Require Node.js Dependencies
const { join } = require("path");
// Require Third-party Dependencies
const { yellow, white } = require("kleur");
const Sequelize = require("sequelize");
const rateLimiter = require("express-rate-limit");
// Require Internal Dependencies
const server = require("./src/httpServer");
const models = require("./src/models");
const initDefaultData = require("./src/initDefaultData");
// ARGV
const [initData = null] = process.argv.slice(2);
// CONSTANTS
const PORT = process.env.PORT || 1338;
const DB_OPTIONS = {
host: process.env.DB_HOST || "localhost",
dialect: process.env.DB_DIALECT || "sqlite",
database: process.env.DB_NAME || "registry",
username: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || null,
logging: false
};
const CLEAN_INTERVAL_MS = 24 * 60 * 60000;
if (process.env.DB_DIALECT === "sqlite") {
DB_OPTIONS.storage = join(__dirname, "database.sqlite");
}
/**
* @async
* @function main
* @returns {Promise<void>}
*/
async function main() {
console.log(white().bold(` > init SQLite database: ${yellow().bold(join(__dirname, "database.sqlite"))}`));
const sequelizeOptions = typeof process.env.DATABASE_URL === "string" ? process.env.DATABASE_URL : DB_OPTIONS;
console.log(sequelizeOptions);
const sequelize = new Sequelize(sequelizeOptions);
const tables = models(sequelize);
let isClosed = false;
await sequelize.sync();
if (initData !== null) {
await initDefaultData(tables);
}
// Cleanup Interval
setInterval(async() => {
const now = new Date().getTime();
try {
const deletedCount = await tables.Users.delete({
where: {
active: false,
createdAt: {
[Sequelize.Op.lt]: now - CLEAN_INTERVAL_MS
}
}
});
console.log(deletedCount);
}
catch (err) {
console.error(err);
}
}, CLEAN_INTERVAL_MS);
server.use(rateLimiter({
windowMs: 60 * 1000,
max: 100
}));
server.use((req, res, next) => {
Object.assign(req, tables);
next();
});
server.listen(PORT, () => {
console.log(white().bold(`HTTP Server is listening on port ${yellow().bold(PORT)}`));
});
/**
* @async
* @function close
* @returns {Promise<void>}
*/
async function close() {
if (isClosed) {
return;
}
isClosed = true;
console.log(white().bold("Exiting HTTP Server!"));
await sequelize.close();
server.server.close();
}
process.once("exit", close);
process.once("SIGINT", close);
}
main().catch(console.error);