-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (47 loc) · 1.88 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
const mongoose = require("mongoose");
//FIXME: REDIS IS MANDATORY, MUST MAKE IT NOT MANDATORY OTHERWISE .cache() and .noCache() will fail
const RedisCache = require("./redisClient.js");
module.exports = async function ({hook, url, options},extras) {
return new Promise(async resolve => {
if (extras?.redis){
RedisCache(
extras.redis.host,
extras.redis.port,
extras.redis.options
)
}else{
// DUCT TAPING SHIT TOGETHER
mongoose.Query.prototype.noCache = function() {return this};
mongoose.Query.prototype.cache = function() {return this};
//Probably won't work
}
console.info("• ".blue, "Connecting to Database...");
const db = mongoose.createConnection(url, options, (err) => {
if (err) return console.error(err, `${"• ".red}Failed to connect to Database!`);
return console.log("• ".green, "Connection OK");
});
const Schemas = require('./schemas.js')(db);
const Virtuals = require('./virtuals.js')(Schemas);
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
db.on("error", console.error.bind(console, "• ".red + "DB connection error:".red));
db.once("open", async () => {
console.log("• ".green, "DB connection successful");
Schemas.collections = Schemas.users.db.collections;
Schemas.raw = Schemas.users.db;
return resolve(Schemas);
});
db.on("reconnected", () => {
if (hook) hook.ok("**RECONNECTED:** Database connection recovered.");
else console.info(" ".blue, "[DB] Reconnected")
});
db.on("reconnectFailed", () => {
if (hook) hook.error("**CRITICAL:** Database shutdown detected. All reconnection attempts failed.");
else console.warn(" ".yellow, "[DB] Reconnect Failed")
});
db.on("disconnected", () => {
if (hook) hook.warn("**ATTENTION:** Database possible shutdown detected. Attempting recovery.");
else console.error(" ".red, "[DB] Disconnected")
});
})
}