fetch-dedupe
Advanced tools
Comparing version 4.0.0-beta.2 to 4.0.0-beta.3
@@ -7,5 +7,80 @@ (function (global, factory) { | ||
var activeRequests = {}; | ||
function CacheMissError() { | ||
var err = Error.apply(this, arguments); | ||
err.name = this.name = 'CacheMissError'; | ||
this.message = err.message; | ||
this.stack = err.stack; | ||
} | ||
CacheMissError.prototype = Object.create(Error.prototype, { | ||
constructor: { | ||
value: CacheMissError, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
var responseCacheStore = {}; | ||
var accessFn = function accessFn() { | ||
return true; | ||
}; | ||
var responseCache = { | ||
get: function get(requestKey) { | ||
if (responseCache.has(requestKey)) { | ||
return responseCacheStore[requestKey].res; | ||
} else { | ||
return undefined; | ||
} | ||
}, | ||
set: function set(requestKey, res) { | ||
responseCacheStore[requestKey] = { | ||
timestamp: Number(new Date()), | ||
res: res | ||
}; | ||
return responseCache; | ||
}, | ||
has: function has(requestKey) { | ||
// `undefined` is not a valid JSON key, so we can reliably use | ||
// it to determine if the value exists or not.dfs | ||
return typeof responseCacheStore[requestKey] !== 'undefined'; | ||
}, | ||
delete: function _delete(requestKey) { | ||
if (!responseCache.has(requestKey)) { | ||
return false; | ||
} else { | ||
delete responseCache[requestKey]; | ||
return true; | ||
} | ||
}, | ||
clear: function clear() { | ||
responseCacheStore = {}; | ||
}, | ||
setCacheCheck: function setCacheCheck(fn) { | ||
if (typeof fn === 'function') { | ||
accssFn = fn; | ||
} else { | ||
throw new TypeError('The first argument to `responseCache.setCacheCheck()` must be a function.'); | ||
} | ||
}, | ||
_useCachedValue: function _useCachedValue(requestKey) { | ||
if (responseCache.has(requestKey)) { | ||
var cacheValue = responseCache.get(requestKey); | ||
var shouldAccess = accessFn(cacheValue.res, cacheValue.timestamp); | ||
if (!shouldAccess) { | ||
responseCache.delete(requestKey); | ||
} | ||
return shouldAccess; | ||
} else { | ||
return false; | ||
} | ||
} | ||
}; | ||
var activeRequests = {}; | ||
function getRequestKey() { | ||
@@ -35,20 +110,2 @@ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
var responseCache = { | ||
get: function get(requestKey) { | ||
return responseCacheStore[requestKey]; | ||
}, | ||
set: function set(requestKey, res) { | ||
responseCacheStore[requestKey] = res; | ||
return responseCacheStore[requestKey]; | ||
}, | ||
has: function has(requestKey) { | ||
// `undefined` is not a valid JSON key, so we can reliably use | ||
// it to determine if the value exists or not.dfs | ||
return typeof responseCacheStore[requestKey] !== 'undefined'; | ||
}, | ||
clear: function clear() { | ||
responseCacheStore = {}; | ||
} | ||
}; | ||
// This loops through all of the handlers for the request and either | ||
@@ -76,17 +133,2 @@ // resolves or rejects them. | ||
function CacheMissError() { | ||
var err = Error.apply(this, arguments); | ||
err.name = this.name = 'CacheMissError'; | ||
this.message = err.message; | ||
this.stack = err.stack; | ||
} | ||
CacheMissError.prototype = Object.create(Error.prototype, { | ||
constructor: { | ||
value: CacheMissError, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
function fetchDedupe(input) { | ||
@@ -139,8 +181,5 @@ var init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var cachedResponse = void 0; | ||
if (appliedCachePolicy !== 'network-only') { | ||
cachedResponse = responseCacheStore[requestKeyToUse]; | ||
if (cachedResponse) { | ||
return Promise.resolve(cachedResponse); | ||
if (responseCache._useCachedValue(requestKeyToUse)) { | ||
return Promise.resolve(responseCache.get(requestKeyToUse)); | ||
} else if (cachePolicy === 'cache-only') { | ||
@@ -189,3 +228,3 @@ var cacheError = new CacheMissError('Response for fetch request not found in cache.'); | ||
res.data = data; | ||
responseCacheStore[requestKeyToUse] = res; | ||
responseCache.set(requestKeyToUse, res); | ||
@@ -221,6 +260,7 @@ if (dedupe) { | ||
exports.responseCache = responseCache; | ||
exports.CacheMissError = CacheMissError; | ||
exports.getRequestKey = getRequestKey; | ||
exports.isRequestInFlight = isRequestInFlight; | ||
exports.clearActiveRequests = clearActiveRequests; | ||
exports.responseCache = responseCache; | ||
exports.fetchDedupe = fetchDedupe; | ||
@@ -227,0 +267,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.FetchDedupe={})}(this,function(e){"use strict";var j={},P={};function K(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=e.url,r=e.method,o=e.responseType,n=void 0===o?"":o,i=e.body,u=void 0===i?"":i;return[void 0===t?"":t,(void 0===r?"":r).toUpperCase(),n,u].join("||")}var t={get:function(e){return P[e]},set:function(e,t){return P[e]=t,P[e]},has:function(e){return void 0!==P[e]},clear:function(){P={}}};function E(e){var t=e.requestKey,r=e.res,o=e.err;(j[t]||[]).forEach(function(e){r?e.resolve(r):e.reject(o)}),j[t]=null}function w(){var e=Error.apply(this,arguments);e.name=this.name="CacheMissError",this.message=e.message,this.stack=e.stack}w.prototype=Object.create(Error.prototype,{constructor:{value:w,writable:!0,configurable:!0}}),e.getRequestKey=K,e.isRequestInFlight=function(e){return!!j[e]},e.clearActiveRequests=function(){j={}},e.responseCache=t,e.fetchDedupe=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=arguments[2],o=void 0,n=void 0;n=r?(o=r,t):t&&(t.responseType||t.dedupe||t.cachePolicy||t.requestKey)?(o=t,{}):(o={},t);var i=o.requestKey,u=o.responseType,s=void 0===u?"":u,c=o.dedupe,a=void 0===c||c,f=o.cachePolicy,d=(n.method||e.method||"").toUpperCase(),v=void 0;v=f||("GET"==d||"OPTIONS"==d||"HEAD"==d||""==d?"cache-first":"network-only");var h=i||K({url:e.url||e,method:n.method||e.method||"",body:n.body||e.body||""}),p=void 0;if("network-only"!==v){if(p=P[h])return Promise.resolve(p);if("cache-only"===f){var l=new w("Response for fetch request not found in cache.");return Promise.reject(l)}}var y=void 0;if(a){j[h]||(j[h]=[]);var m=j[h],q=!!m.length,b={};if(y=new Promise(function(e,t){b.resolve=e,b.reject=t}),m.push(b),q)return y}var g=fetch(e,n).then(function(t){var e=void 0;return e=s instanceof Function?s(t):s||(204===t.status?"text":"json"),t[e]().then(function(e){if(t.data=e,P[h]=t,!a)return t;E({requestKey:h,res:t})},function(){if(t.data=null,!a)return t;E({requestKey:h,res:t})})},function(e){if(!a)return Promise.reject(e);E({requestKey:h,err:e})});return a?y:g},Object.defineProperty(e,"__esModule",{value:!0})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.FetchDedupe={})}(this,function(e){"use strict";function b(){var e=Error.apply(this,arguments);e.name=this.name="CacheMissError",this.message=e.message,this.stack=e.stack}b.prototype=Object.create(Error.prototype,{constructor:{value:b,writable:!0,configurable:!0}});var r={},q={get:function(e){return q.has(e)?r[e].res:void 0},set:function(e,t){return r[e]={timestamp:+new Date,res:t},q},has:function(e){return void 0!==r[e]},delete:function(e){return!!q.has(e)&&(delete q[e],!0)},clear:function(){r={}},setCacheCheck:function(e){if("function"!=typeof e)throw new TypeError("The first argument to `responseCache.setCacheCheck()` must be a function.");accssFn=e},_useCachedValue:function(e){if(q.has(e)){q.get(e);return!0}return!1}},j={};function w(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=e.url,r=e.method,n=e.responseType,o=void 0===n?"":n,s=e.body,i=void 0===s?"":s;return[void 0===t?"":t,(void 0===r?"":r).toUpperCase(),o,i].join("||")}function E(e){var t=e.requestKey,r=e.res,n=e.err;(j[t]||[]).forEach(function(e){r?e.resolve(r):e.reject(n)}),j[t]=null}e.responseCache=q,e.CacheMissError=b,e.getRequestKey=w,e.isRequestInFlight=function(e){return!!j[e]},e.clearActiveRequests=function(){j={}},e.fetchDedupe=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=arguments[2],n=void 0,o=void 0;o=r?(n=r,t):t&&(t.responseType||t.dedupe||t.cachePolicy||t.requestKey)?(n=t,{}):(n={},t);var s=n.requestKey,i=n.responseType,u=void 0===i?"":i,c=n.dedupe,a=void 0===c||c,f=n.cachePolicy,d=(o.method||e.method||"").toUpperCase(),h=void 0;h=f||("GET"==d||"OPTIONS"==d||"HEAD"==d||""==d?"cache-first":"network-only");var p=s||w({url:e.url||e,method:o.method||e.method||"",body:o.body||e.body||""});if("network-only"!==h){if(q._useCachedValue(p))return Promise.resolve(q.get(p));if("cache-only"===f){var v=new b("Response for fetch request not found in cache.");return Promise.reject(v)}}var l=void 0;if(a){j[p]||(j[p]=[]);var y=j[p],m=!!y.length,g={};if(l=new Promise(function(e,t){g.resolve=e,g.reject=t}),y.push(g),m)return l}var C=fetch(e,o).then(function(t){var e=void 0;return e=u instanceof Function?u(t):u||(204===t.status?"text":"json"),t[e]().then(function(e){if(t.data=e,q.set(p,t),!a)return t;E({requestKey:p,res:t})},function(){if(t.data=null,!a)return t;E({requestKey:p,res:t})})},function(e){if(!a)return Promise.reject(e);E({requestKey:p,err:e})});return a?l:C},Object.defineProperty(e,"__esModule",{value:!0})}); |
@@ -0,3 +1,7 @@ | ||
import CacheMissError from './cache-miss-error'; | ||
import responseCache from './response-cache'; | ||
export { responseCache, CacheMissError }; | ||
var activeRequests = {}; | ||
var responseCacheStore = {}; | ||
@@ -28,20 +32,2 @@ export function getRequestKey() { | ||
export var responseCache = { | ||
get: function get(requestKey) { | ||
return responseCacheStore[requestKey]; | ||
}, | ||
set: function set(requestKey, res) { | ||
responseCacheStore[requestKey] = res; | ||
return responseCacheStore[requestKey]; | ||
}, | ||
has: function has(requestKey) { | ||
// `undefined` is not a valid JSON key, so we can reliably use | ||
// it to determine if the value exists or not.dfs | ||
return typeof responseCacheStore[requestKey] !== 'undefined'; | ||
}, | ||
clear: function clear() { | ||
responseCacheStore = {}; | ||
} | ||
}; | ||
// This loops through all of the handlers for the request and either | ||
@@ -69,17 +55,2 @@ // resolves or rejects them. | ||
function CacheMissError() { | ||
var err = Error.apply(this, arguments); | ||
err.name = this.name = 'CacheMissError'; | ||
this.message = err.message; | ||
this.stack = err.stack; | ||
} | ||
CacheMissError.prototype = Object.create(Error.prototype, { | ||
constructor: { | ||
value: CacheMissError, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
export function fetchDedupe(input) { | ||
@@ -132,8 +103,5 @@ var init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var cachedResponse = void 0; | ||
if (appliedCachePolicy !== 'network-only') { | ||
cachedResponse = responseCacheStore[requestKeyToUse]; | ||
if (cachedResponse) { | ||
return Promise.resolve(cachedResponse); | ||
if (responseCache._useCachedValue(requestKeyToUse)) { | ||
return Promise.resolve(responseCache.get(requestKeyToUse)); | ||
} else if (cachePolicy === 'cache-only') { | ||
@@ -182,3 +150,3 @@ var cacheError = new CacheMissError('Response for fetch request not found in cache.'); | ||
res.data = data; | ||
responseCacheStore[requestKeyToUse] = res; | ||
responseCache.set(requestKeyToUse, res); | ||
@@ -185,0 +153,0 @@ if (dedupe) { |
'use strict'; | ||
exports.__esModule = true; | ||
exports.CacheMissError = exports.responseCache = undefined; | ||
exports.getRequestKey = getRequestKey; | ||
@@ -8,4 +9,18 @@ exports.isRequestInFlight = isRequestInFlight; | ||
exports.fetchDedupe = fetchDedupe; | ||
var _cacheMissError = require('./cache-miss-error'); | ||
var _cacheMissError2 = _interopRequireDefault(_cacheMissError); | ||
var _responseCache = require('./response-cache'); | ||
var _responseCache2 = _interopRequireDefault(_responseCache); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
exports.responseCache = _responseCache2.default; | ||
exports.CacheMissError = _cacheMissError2.default; | ||
let activeRequests = {}; | ||
let responseCacheStore = {}; | ||
@@ -31,23 +46,2 @@ function getRequestKey({ | ||
const responseCache = exports.responseCache = { | ||
get(requestKey) { | ||
return responseCacheStore[requestKey]; | ||
}, | ||
set(requestKey, res) { | ||
responseCacheStore[requestKey] = res; | ||
return responseCacheStore[requestKey]; | ||
}, | ||
has(requestKey) { | ||
// `undefined` is not a valid JSON key, so we can reliably use | ||
// it to determine if the value exists or not.dfs | ||
return typeof responseCacheStore[requestKey] !== 'undefined'; | ||
}, | ||
clear() { | ||
responseCacheStore = {}; | ||
} | ||
}; | ||
// This loops through all of the handlers for the request and either | ||
@@ -71,17 +65,2 @@ // resolves or rejects them. | ||
function CacheMissError() { | ||
var err = Error.apply(this, arguments); | ||
err.name = this.name = 'CacheMissError'; | ||
this.message = err.message; | ||
this.stack = err.stack; | ||
} | ||
CacheMissError.prototype = Object.create(Error.prototype, { | ||
constructor: { | ||
value: CacheMissError, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
function fetchDedupe(input, init = {}, dedupeOptions) { | ||
@@ -123,10 +102,7 @@ let opts, initToUse; | ||
let cachedResponse; | ||
if (appliedCachePolicy !== 'network-only') { | ||
cachedResponse = responseCacheStore[requestKeyToUse]; | ||
if (cachedResponse) { | ||
return Promise.resolve(cachedResponse); | ||
if (_responseCache2.default._useCachedValue(requestKeyToUse)) { | ||
return Promise.resolve(_responseCache2.default.get(requestKeyToUse)); | ||
} else if (cachePolicy === 'cache-only') { | ||
const cacheError = new CacheMissError(`Response for fetch request not found in cache.`); | ||
const cacheError = new _cacheMissError2.default(`Response for fetch request not found in cache.`); | ||
return Promise.reject(cacheError); | ||
@@ -173,3 +149,3 @@ } | ||
res.data = data; | ||
responseCacheStore[requestKeyToUse] = res; | ||
_responseCache2.default.set(requestKeyToUse, res); | ||
@@ -176,0 +152,0 @@ if (dedupe) { |
{ | ||
"name": "fetch-dedupe", | ||
"version": "4.0.0-beta.2", | ||
"version": "4.0.0-beta.3", | ||
"description": "A thin wrapper around fetch that prevents duplicate requests.", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
@@ -98,3 +98,5 @@ # Fetch Dedupe | ||
- `.has()` | ||
- `.delete()` | ||
- `.clear()` | ||
- `.setCacheCheck()` | ||
- `isRequestInFlight()` | ||
@@ -208,3 +210,3 @@ - `clearActiveRequests()` | ||
Call this to manually update the cached value of `requestKey` with `res`. | ||
Call this to manually update the cached value of `requestKey` with `res`. Returns the `responseCache`. | ||
@@ -218,2 +220,7 @@ > Note: this is an advanced method, and you generally do not need to manually update the store. | ||
##### `responseCache.delete( requestKey )` | ||
Deletes the cached value associated with `requestKey`. Returns `false` if the value did not | ||
exist in the cache, or `true` if it existed and has been deleted. | ||
##### `responseCache.clear()` | ||
@@ -223,2 +230,28 @@ | ||
##### `responseCache.setCacheCheck( fn )` | ||
By default, fetch-dedupe caches responses indefinitely. You can customize this behavior by calling this | ||
method a single time when your app is initialized. | ||
This function accepts a single argument, `fn,` which is a function. This function will be called any time | ||
that a request is made that has a cached response. It receives two arguments: `cachedResponse, timestamp`. Return | ||
`true` to use the cached response, or `false` to remove the value from the cache and make a network request | ||
instead. | ||
For instance, to invalidate cached responses after 10 seconds: | ||
```js | ||
import { responseCache } from 'fetch-dedupe'; | ||
// 1000 = 1 second in milliseconds | ||
// * 60 = 1 minute | ||
// * 10 = 10 minutes | ||
const TEN_MINUTES = 1000 * 60 * 10; | ||
responseCache.setCacheCheck((cachedResponse, timestamp) => { | ||
const currentTimestamp = Number(new Date()); | ||
return currentTimestamp - timestamp <= TEN_MINUTES; | ||
}); | ||
``` | ||
##### `isRequestInFlight( requestKey )` | ||
@@ -250,2 +283,4 @@ | ||
> Note: it is very unlikely that you would ever need to call this method. | ||
### Guides | ||
@@ -252,0 +287,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
40982
12
668
368