Browse Source

Cache responses

pull/6/head
Luke Childs 9 years ago
parent
commit
14ed37aca9
  1. 1
      package.json
  2. 28
      src/index.js

1
package.json

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

28
src/index.js

@ -1,4 +1,7 @@
const request = require('request');
const request = require('request');
const NodeCache = require('node-cache');
const cache = new NodeCache();
const baseUrl = 'https://onionoo.torproject.org/';
const endpoints = [
@ -10,14 +13,33 @@ const endpoints = [
'uptime'
];
function checkResponseCache(response) {
const cacheControl = response.headers['cache-control'];
const maxAgeRegex = /max-age=(\d+)/;
const maxAge = cacheControl && cacheControl.match(maxAgeRegex);
return maxAge && maxAge[1];
}
module.exports = endpoints.reduce((onionoo, endpoint) => {
onionoo[endpoint] = args => new Promise((resolve, reject) => {
request({
const requestOptions = {
uri: `${baseUrl}${endpoint}`,
qs: args,
json: true
}, (error, response, body) => {
};
const cacheKey = JSON.stringify(requestOptions);
const cachedResult = cache.get(cacheKey);
if(cachedResult) {
resolve(cachedResult);
}
request(requestOptions, (error, response, body) => {
if (!error && response.statusCode == 200) {
const ttl = checkResponseCache(response);
if(ttl) {
cache.set(cacheKey, body, ttl);
}
resolve(body);
} else {
reject(error || {

Loading…
Cancel
Save