Skip to content

Commit

Permalink
Merge branch 'master' of github.com:Restocks/http-config-cache
Browse files Browse the repository at this point in the history
  • Loading branch information
worm-emoji committed Oct 31, 2016
2 parents 5096b91 + 8a89eba commit 762a316
Show file tree
Hide file tree
Showing 4 changed files with 1,099 additions and 15 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
62 changes: 62 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'use strict';

var request = require('request');
var Timedcache = require('timed-cache');

var cache = new Timedcache();

var fetchObject = function fetchObject(url) {
return new Promise(function (resolve, reject) {
var retries = 0;

var URLResponseHandler = function URLResponseHandler(err, res, body) {
if (err) {
setTimeout(function () {
retries += 1;
if (retries > 3) {
reject('Unable to fetch data');
} else {
/* eslint-disable no-console */
console.warn('[http-config-cache]: reattempting JSON fetch, after failed attempt #' + retries);
/* eslint-enable no-console */
request(url, URLResponseHandler);
}
}, 750);
} else {
var configObject = null;
try {
configObject = JSON.parse(body);
} catch (e) {
reject('Data not valid JSON');
}
resolve(configObject);
}
};

request(url, URLResponseHandler);
});
};

module.exports = function (url, time, ignoreCache) {
return new Promise(function (resolve, reject) {
var cacheResponse = cache.get(url);
if (typeof cacheResponse === 'undefined' || ignoreCache) {
fetchObject(url).then(function (cacheObject) {
var cacheConfig = {};

if (typeof time === 'number') {
cacheConfig.ttl = time;
} else {
cacheConfig.ttl = 600000;
}

cache.put(url, cacheObject, cacheConfig);
resolve(cacheObject);
}).catch(function (err) {
reject(err);
});
} else {
resolve(cacheResponse);
}
});
};
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
"name": "http-config-cache",
"version": "1.0.2",
"description": "Cache a remote config! Supports JSON.",
"main": "src/index.js",
"main": "lib/index.js",
"scripts": {
"test": "./node_modules/.bin/mocha --reporter spec --timeout 25000",
"build": "babel src -d lib",
"test": "npm run build && ./node_modules/.bin/mocha --reporter spec --timeout 25000",
"lint": "./node_modules/.bin/eslint src/"
},
"repository": {
Expand All @@ -18,6 +19,8 @@
},
"homepage": "https://github.com/Restocks/http-config-cache#readme",
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-preset-es2015": "^6.18.0",
"eslint": "^3.8.1",
"eslint-config-airbnb-base": "^9.0.0",
"eslint-plugin-import": "^2.0.1",
Expand Down
Loading

0 comments on commit 762a316

Please sign in to comment.