@nutgaard/use-fetch
Version:
A useFetch hook to be used with react@^16.8.0
62 lines • 2.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var FetchCache = /** @class */ (function () {
function FetchCache() {
this.cache = {};
this.resolvedCache = {};
}
FetchCache.prototype.fetch = function (key, url, init) {
var _this = this;
if (this.hasKey(key)) {
return this.get(key);
}
var result = fetch(url, init);
this.put(key, result);
result.then(function (resp) {
if (!resp.ok) {
_this.remove(key);
}
}, function () {
_this.remove(key);
});
return result.then(function (resp) { return resp.clone(); });
};
FetchCache.prototype.get = function (key) {
return this.cache[key].then(function (resp) { return resp.clone(); });
};
FetchCache.prototype.getResolved = function (key) {
return this.resolvedCache[key];
};
FetchCache.prototype.putResolved = function (key, value) {
this.resolvedCache[key] = value;
};
FetchCache.prototype.put = function (key, value) {
this.cache[key] = value.then(function (resp) { return resp.clone(); });
};
FetchCache.prototype.remove = function (key) {
delete this.cache[key];
delete this.resolvedCache[key];
};
FetchCache.prototype.clear = function () {
this.cache = {};
this.resolvedCache = {};
};
FetchCache.prototype.hasKey = function (key) {
// tslint:disable-next-line:strict-type-predicates
return this.cache[key] !== undefined;
};
FetchCache.prototype.keys = function () {
return Object.keys(this.cache);
};
FetchCache.prototype.hasKeyResolved = function (key) {
// tslint:disable-next-line:strict-type-predicates
return this.resolvedCache[key] !== undefined;
};
FetchCache.prototype.size = function () {
return Object.keys(this.cache).length;
};
return FetchCache;
}());
var globaleFetchCache = new FetchCache();
exports.default = globaleFetchCache;
//# sourceMappingURL=fetch-cache.js.map