Browse Source

Swap out request for got

pull/6/head
Luke Childs 8 years ago
parent
commit
8cc1ab21c6
  1. 4
      package.json
  2. 52
      src/index.js

4
package.json

@ -24,7 +24,7 @@
}, },
"homepage": "https://github.com/lukechilds/onionoo-node-client#readme", "homepage": "https://github.com/lukechilds/onionoo-node-client#readme",
"dependencies": { "dependencies": {
"node-cache": "^3.2.1", "got": "^6.3.0",
"request": "^2.74.0" "node-cache": "^3.2.1"
} }
} }

52
src/index.js

@ -1,9 +1,10 @@
const request = require('request'); const got = require('got');
const NodeCache = require('node-cache'); const NodeCache = require('node-cache');
const querystring = require('querystring');
const cache = new NodeCache(); const cache = new NodeCache();
const baseUrl = 'https://onionoo.torproject.org/'; const baseUrl = 'https://onionoo.torproject.org';
const endpoints = [ const endpoints = [
'summary', 'summary',
'details', 'details',
@ -22,33 +23,30 @@ function checkResponseCache(response) {
module.exports = endpoints.reduce((onionoo, endpoint) => { module.exports = endpoints.reduce((onionoo, endpoint) => {
onionoo[endpoint] = args => new Promise((resolve, reject) => { onionoo[endpoint] = args => new Promise((resolve, reject) => {
const requestOptions = {
uri: `${baseUrl}${endpoint}`, // Build url
qs: args, const url = `${baseUrl}/${endpoint}?${querystring.encode(args)}`;
json: true,
gzip: true // Check for url in cache
}; const cachedResult = cache.get(url);
const cacheKey = JSON.stringify(requestOptions);
const cachedResult = cache.get(cacheKey);
if(cachedResult) { if(cachedResult) {
resolve(cachedResult); resolve(cachedResult);
} } else {
request(requestOptions, (error, response, body) => { // Make request
if (!error && response.statusCode == 200) { resolve(got(url, { json: true })
const ttl = checkResponseCache(response); .then(response => {
if(ttl) {
cache.set(cacheKey, body, ttl); // Cache response
} const ttl = checkResponseCache(response);
resolve(body); if(ttl) {
} else { cache.set(url, response.body, ttl);
reject(error || { }
statusCode: response.statusCode,
statusMessage: response.statusMessage // Resolve response
}); return response.body;
} }));
}) }
}); });
return onionoo; return onionoo;

Loading…
Cancel
Save