forked from ChaitanyaLKulkarni/COCBot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.js
103 lines (97 loc) · 2.65 KB
/
db.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
const { MongoClient } = require("mongodb");
let client = null;
let matchInfo = null;
let commandsInfo = null;
let db = null;
const init = async () => {
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.lduex.mongodb.net/bot?retryWrites=true&w=majority`;
client = new MongoClient(uri, { useUnifiedTopology: true });
await client.connect();
db = client.db("bot");
matchInfo = db.collection("matches");
commandsInfo = db.collection("commands");
};
const getAll = async () => {
const cursor = matchInfo.find({});
if ((await cursor.count()) === 0) {
console.log("No documents found!");
}
const op = [];
await cursor.forEach((m) => {
op.push(m);
});
return op;
};
const addMatch = async (channelName, matchId, removeCurrent = false) => {
const chobj = await getChannelMatches(channelName);
let prev = [];
if (chobj) {
prev = chobj["prevMatches"];
if (chobj["currentMatch"] !== "" && !removeCurrent) {
prev.unshift(chobj["currentMatch"]);
}
}
const query = {
$set: {
currentMatch: matchId,
prevMatches: prev,
},
};
const op = await matchInfo.updateOne({ _id: channelName }, query, {
upsert: true,
});
return op;
};
const removeCurrentMatch = async (channelName) => {
const op = await matchInfo.updateOne(
{ _id: channelName },
{ $set: { currentMatch: "" } }
);
return op;
};
const getChannelMatches = async (channelName) => {
const op = await matchInfo.findOne({ _id: channelName });
return op;
};
const getChannelCommands = async (channelName) => {
const op = await commandsInfo.findOne({ _id: channelName });
return op;
};
const addCommand = async (channelName, command, response) => {
const op = await commandsInfo.updateOne(
{ _id: channelName },
{ $set: { [command]: response } },
{ upsert: true }
);
return op;
};
const getCommands = async () => {
const cursor = commandsInfo.find({});
if ((await cursor.count()) === 0) {
console.log("No documents found!");
}
const op = {};
await cursor.forEach((m) => {
const channelName = m._id;
delete m._id;
op[channelName] = { ...m };
});
return op;
};
const removeCommand = async (channelName, command) => {
const op = await commandsInfo.updateOne(
{ _id: channelName },
{ $unset: { [command]: "" } }
);
};
module.exports = {
init,
getAll,
addMatch,
removeCurrentMatch,
getChannelMatches,
getChannelCommands,
addCommand,
getCommands,
removeCommand,
};