-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmongo-updater.js
231 lines (202 loc) · 7.81 KB
/
mongo-updater.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*
This script runs a local REST-ish server that can be used to update user & trade details in MongoDB.
The server will run on port secrets.mongoUpdaterPort and update the DB at secrets.mongoUri.
*/
var mongodb = require('mongodb');
var express = require('express');
var winston = require('winston');
var async = require('async');
var moment = require('moment');
var bodyParser = require('body-parser');
var secrets = require('./secrets.js').secrets;
var winstonOpts = { timestamp: true, colorize: false, level: 'info' };
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, winstonOpts);
var app = express();
app.use(bodyParser.json());
mongodb.connect(secrets.mongoUri, function (err, dbClient) {
if (err) {
winston.err('Error connecting to MongoDB:', err);
process.exit(1);
}
// GET /user/<userId> - returns user record as JSON
app.get('/user/:userId', function (req, res) {
var userId = req.params.userId;
winston.info("GET /user/" + userId);
getCollection(dbClient, 'users', res, function(collection) {
collection.findOne({ _id: userId }, function (err, record) {
if (err) {
winston.error('Error finding user ' + userId + ':', err);
res.status(500).send('Error finding user ' + userId);
return;
}
record ? res.json(record) : res.status(404).send('No user found with id ' + userId);
});
});
});
// GET /users/friends - returns JSON list of all user details with isFriend set to true
app.get('/users/friends', function (req, res) {
winston.info("GET /users/friends");
getCollection(dbClient, 'users', res, function(collection) {
collection.find({ isFriend: true }).toArray(function (err, results) {
if (err) {
winston.error('Error finding friends :', err);
res.status(500).send('Error finding friends');
return;
}
res.json(results);
});
});
});
// GET /daily-trades/<id> - get today's daily trades record as JSON
//app.get('/daily-trades/:userId/:day', function (req, res) {
app.get('/daily-trades/:userId', function (req, res) {
var userId = req.params.userId;
//var day = req.params.day;
var day = moment().format('YYYY-MM-DD');
winston.info("GET /daily-trades/" + userId);
getCollection(dbClient, 'daily-trades', res, function(collection) {
collection.findOne({ userId: userId, day: day }, function (err, record) {
if (err) {
winston.error('Error finding daily trades for user ' + userId + ' and day ' + day + ':', err);
res.status(500).send('Error finding daily trades for user ' + userId + ' and day ' + day);
return;
}
res.json(record); // Return null if nothing is found for the user/day
});
});
});
// POST /user/<id>/added - updates user record: set isFriend to true, set lastAddedTime to now, increment numTimesAdded
app.post('/user/:userId/added', function (req, res) {
var userId = req.params.userId;
winston.info("POST /user/" + userId + "/added");
getCollection(dbClient, 'users', res, function(collection) {
var updates = { $set: { isFriend: true, lastAddedTime: new Date().getTime() }, $inc: { numTimesAdded: 1 } };
collection.update({ _id: userId }, updates, { upsert: true }, function (err) {
if (err) {
winston.error('Error updating added user details ' + userId + ':', err);
res.status(500).send('Error updating added user details ' + userId);
return;
}
res.status(204).send();
});
});
});
// POST /user/<id>/removed - set isFriend to false
app.post('/user/:userId/removed', function (req, res) {
var userId = req.params.userId;
winston.info("POST /user/" + userId + "/removed");
getCollection(dbClient, 'users', res, function(collection) {
var updates = { $set: { isFriend: false } };
collection.update({ _id: userId }, updates, function (err) {
if (err) {
winston.error('Error updating removed user details ' + userId + ':', err);
res.status(500).send('Error updating removed user details ' + userId);
return;
}
res.status(204).send();
});
});
});
// POST /user/<id>/trade-declined - update user record: increment numTradesDeclined
app.post('/user/:userId/trade-declined', function (req, res) {
var userId = req.params.userId;
winston.info("POST /user/" + userId + "/trade-declined");
getCollection(dbClient, 'users', res, function(collection) {
var updates = { $inc: { numTradesDeclined: 1 } };
collection.update({ _id: userId }, updates, function (err) {
if (err) {
winston.error('Error updating declined trade user details ' + userId + ':', err);
res.status(500).send('Error updating declined trade user details ' + userId);
return;
}
res.status(204).send();
});
});
});
// POST /user/<id>/trade-accepted - update user record: increment numTradesAccepted
app.post('/user/:userId/trade-accepted', function (req, res) {
var userId = req.params.userId;
winston.info("POST /user/" + userId + "/trade-accepted");
getCollection(dbClient, 'users', res, function(collection) {
var updates = { $inc: { numTradesAccepted: 1 } };
collection.update({ _id: userId }, updates, function (err) {
if (err) {
winston.error('Error updating accepted trade user details ' + userId + ':', err);
res.status(500).send('Error updating accepted trade user details ' + userId);
return;
}
res.status(204).send();
});
});
});
// POST /trade/<userId>/<tradeId>/<itemId>/<wasClaimed>
// body contains JSON details: { name: "item name" }
// - update trade record, set time to now
// - update user record, increment numItemsClaimed or numItemsDonated
// - update daily trades record, increment numItemsClaimed or numItemsDonated
app.post('/trade/:userId/:tradeId/:itemId/:wasClaimed', function (req, res) {
var userId = req.params.userId;
var tradeId = req.params.tradeId;
var itemId = req.params.itemId;
var wasClaimed = req.params.wasClaimed == 'true';
winston.info("POST /trade/" + userId + "/" + tradeId + "/" + "itemId" + "/" + wasClaimed);
winston.info("POST body", req.body);
var incUpdates = { $inc: {} };
if (wasClaimed) {
incUpdates['$inc'].numItemsClaimed = 1;
}
else {
incUpdates['$inc'].numItemsDonated = 1;
}
async.parallel([
function (callback) {
getCollection(dbClient, 'daily-trades', res, function(collection) {
var day = moment().format('YYYY-MM-DD');
collection.update({ userId: userId, day: day }, incUpdates, { upsert: true }, callback);
});
},
function (callback) {
getCollection(dbClient, 'trades', res, function(collection) {
var tradeRecord = {
userId: userId,
tradeId: tradeId,
time: new Date().getTime(),
itemId: itemId,
wasClaimed: wasClaimed
};
if (req.body && req.body.name) {
tradeRecord.itemName = req.body.name;
}
collection.insert(tradeRecord, callback);
});
},
function (callback) {
getCollection(dbClient, 'users', res, function(collection) {
collection.update({ _id: userId }, incUpdates, callback);
});
}
], function(err, results) {
if (err) {
winston.error('Error updating details for trade ' + userId + '/' + tradeId + '/' + itemId + '/' + wasClaimed + ':', err);
res.status(500).send('Error updating details for trade ' + userId + '/' + tradeId + '/' + itemId + '/' + wasClaimed);
return;
}
res.status(204).send();
});
});
app.listen(secrets.mongoUpdaterPort, function () {
winston.info('Mongo updater server listening on port ' + secrets.mongoUpdaterPort);
});
});
// Helper function to return a collection or set a 500 response
function getCollection(client, collectionName, res, callback) {
client.collection(collectionName, function (err, collection) {
if (err) {
winston.error('Error loading ' + collectionName + ' collection:', err);
res.status(500).send('Error loading ' + collectionName + ' collection');
return;
}
callback(collection)
});
}