This repository has been archived by the owner on Feb 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
101 lines (86 loc) · 2.69 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
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
var Promise = require('promise');
var config = require('./shariff.json');
var cache = {};
/**
* Returns the counts for the given url on success. Keeps an internal
* cache of the results which expires based on the expiresIn config value
*
* @param String url URL to search for counts
* @param bool noCache If true, the request bypasses the cache
*
* @return Promise Promise resolving to an object containing the counts
* or an error on reject
*/
function getCounts(url, noCache) {
var services = [
require('./lib/facebook'),
require('./lib/googleplus'),
require('./lib/flattr'),
require('./lib/linkedin'),
require('./lib/reddit'),
require('./lib/stumbleupon'),
require('./lib/xing')
];
var cached = cache[url];
if (!noCache && cached && cached.expire > new Date())
return Promise.resolve(cached.counts);
var requests = services.map(function(service) {
return new Promise(function(resolve, reject) {
service.request(url, function(error, response, body) {
if ( !error && response.statusCode === 200 ) {
if ( typeof body === "object" ) {
resolve(body);
} else {
resolve(JSON.parse(body));
}
} else {
reject(error);
}
});
});
});
// res: Array of result objects
function extractCounts(res) {
return new Promise(function(resolve, reject) {
var result = {};
var i = 0;
res.forEach(function() {
var count = services[i].extractCount(res[i]);
result[ services[i].name ] = count;
i++;
});
resolve(result);
});
}
return Promise
.all(requests)
.then(extractCounts)
.then(toJSON)
.then(function(counts) {
cache[url] = {
expire: +new Date() + config.cache.expiresIn,
counts: counts
};
return Promise.resolve(counts);
}, function(err) {
return Promise.reject(err);
});
}
function toJSON(data) {
return new Promise(function(resolve, reject) {
try {
var jsonString = JSON.stringify(data);
if (jsonString && typeof jsonString === "string") {
resolve(jsonString);
} else {
throw "Failed generating JSON string.";
}
}
catch(e) {
reject(Error(e));
}
});
}
module.exports = {
getCounts: getCounts
};