-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserFetcher.js
69 lines (66 loc) · 1.81 KB
/
UserFetcher.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
/* @flow */
var _ = require('underscore');
var BaseURL = require('./BaseURL');
var superagent = require('superagent');
var UserFetcher = {
// callback(err, user)
fetchUser: function(userID, callback) {
this.fetchUsers([userID], function(err, usersByID) {
callback(err, usersByID ? usersByID[userID] : null);
});
},
// callback(err, userByID)
fetchUsers: function(userIDs, callback) {
var results = {};
var userIDsToFetch = [];
_.each(userIDs, function(userID) {
var cachedUser = this.userCache_[userID];
if (cachedUser) {
results[userID] = cachedUser;
} else {
userIDsToFetch.push(userID);
}
}, this);
if (_.isEmpty(userIDsToFetch)) {
callback(null, results);
return;
}
this.fetchUsersFromServer(userIDsToFetch, function(err, usersByID) {
if (err) {
callback(err, null);
return;
}
this.userCache_ = _.extend(this.userCache_, usersByID);
results = _.extend(results, usersByID);
callback(null, results);
}.bind(this));
},
getUsers: function(userIDs) {
var userByID = {};
_.each(userIDs, function(userID) {
var user = this.userCache_[userID];
if (user) {
userByID[userID] = user;
}
}, this);
return userByID;
},
ensureUsers: function(userIDs) {
this.fetchUsers(userIDs, function() {});
},
// private
userCache_: {},
fetchUsersFromServer: function(userIDs, callback) {
var encodedUserIDs = userIDs.join(',');
superagent.get(BaseURL + '/api/user/' + encodedUserIDs)
.end(function(res) {
if (!res.ok) {
console.log('error fetching users: ', res.text);
callback(res.text || '', null);
return;
}
callback(null, res.body);
});
},
};
module.exports = UserFetcher;