-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
184 lines (158 loc) · 4.54 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
'use strict';
const { MongoClient } = require('mongodb');
const { MONGODB_URI } = process.env;
let dbPromise;
module.exports = {
async connectToDB(uri) {
const client = await MongoClient
.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(err => {
console.error('MongoDB connection error:', err);
throw err;
});
process.on('exit', () => {
console.log('Closing MongoDB connection...');
client.close(false);
});
const db = client.db();
return db;
},
async db() {
if (!dbPromise) {
dbPromise = this.connectToDB(MONGODB_URI);
}
return dbPromise;
},
async collection(name) {
return (await this.db()).collection(name);
},
// Users
async getUser(id) {
return (await this.collection('users'))
.aggregate([
{ $match: { id } },
{
$lookup: {
from: 'characters',
foreignField: 'id',
localField: 'characterId',
as: 'character',
},
},
{ $unwind: { path: '$character', preserveNullAndEmptyArrays: true } },
])
.toArray()
.then(result => result[0]);
},
async updateUser(userData) {
return (await this.collection('users'))
.findOneAndUpdate(
{ id: userData.id },
{ $set: userData },
{ upsert: true, returnOriginal: false })
.then(result => result.value);
},
// Characters
async updateCharacter(charData) {
return (await this.collection('characters'))
.findOneAndUpdate(
{ id: charData.id },
{ $set: charData },
{ upsert: true, returnOriginal: false })
.then(result => result.value);
},
async getTopRoomsVisited(limit) {
return (await this.collection('characters'))
.aggregate([
{
$lookup: {
from: 'moves',
foreignField: 'characterId',
localField: 'id',
as: 'moves',
},
},
{ $unwind: '$moves' },
{ $group: { _id: { id: '$id', name: '$name', to: '$moves.to' } } },
{ $group: { _id: '$_id.id', moves: { $sum: 1 }, name: { $first: '$_id.name' } } },
{ $sort: { moves: -1 } },
{ $limit: limit || 5 },
])
.toArray();
},
async getTopMoves(limit) {
return (await this.collection('characters'))
.aggregate([
{ $lookup: { from: 'moves', foreignField: 'characterId', localField: 'id', as: 'moves' } },
{ $project: { name: 1, moves: { $size: '$moves' } } },
{ $match: { moves: { $gt: 0 } } },
{ $sort: { moves: -1 } },
{ $limit: limit || 5 },
])
.toArray();
},
async getTopCoconutsReturned(limit) {
return (await this.collection('characters'))
.find({ coconutsReturned: { $gt: 0 } })
.sort({ coconutsReturned: -1 })
.limit(limit || 5)
.toArray();
},
// Rooms
async getRoom(coords) {
return (await this.collection('rooms'))
.aggregate([
{ $match: { coords } },
{
$lookup: {
from: 'users',
pipeline: [
{ $match: {} },
{
$lookup: {
from: 'characters',
foreignField: 'id',
localField: 'characterId',
as: 'character',
},
},
{ $unwind: '$character' },
{ $match: { 'character.currentRoom': coords } },
],
as: 'users',
},
},
])
.toArray()
.then(results => results[0]);
},
async updateRoom(roomData) {
return (await this.collection('rooms'))
.findOneAndUpdate(
{ coords: roomData.coords },
{ $set: roomData },
{ upsert: true, returnOriginal: false })
.then(result => result.value);
},
// Moves
async addMove(characterId, from, to) {
return (await this.collection('moves')).insertOne({ characterId, from, to });
},
async getRoomMoves(coords) {
return (await this.collection('moves'))
.aggregate([
{ $match: { $or: [{ from: coords }, { to: coords }] } },
{ $project: { room: ['$from', '$to'] } },
{ $unwind: '$room' },
{ $match: { room: { $ne: coords } } },
{ $group: { _id: '$room', count: { $sum: 1 } } },
{ $project: { x: { $first: '$_id' }, y: { $last: '$_id' }, count: 1 } },
])
.toArray();
},
// Messages
async logMessage(userId, content) {
return (await this.collection('messages'))
.insertOne({ userId, content });
},
};