react-http-fetch
Version:
An http library for React JS built on top of native JS fetch
108 lines (107 loc) • 3.56 kB
JavaScript
var HttpCacheService = /** @class */ (function () {
function HttpCacheService(store) {
this.prefixedStore = store;
}
/**
* Gets the unique key used as idenitifier to store
* a cached response for the given http request.
*/
HttpCacheService.prototype.getRequestIdentifier = function (request) {
var fullUrl = request.urlWithParams;
return fullUrl;
};
/**
* Tells if a cached entry is expired.
*/
HttpCacheService.prototype.isEntryExpired = function (entry) {
var nowTime = new Date().getTime();
var cachedAtDate = entry.cachedAt instanceof Date ? entry.cachedAt : new Date(entry.cachedAt);
var cachedTime = cachedAtDate.getTime();
return cachedTime + entry.maxAge < nowTime;
};
/**
* Gets the cached entry associated with the request.
*/
HttpCacheService.prototype.getEntry = function (request) {
var reqIdentifier = this.getRequestIdentifier(request);
return this.prefixedStore.get(reqIdentifier);
};
/**
* Removes a cached entry.
*/
HttpCacheService.prototype.removeEntry = function (entry) {
this.prefixedStore.delete(entry.identifier);
};
/**
* Determines if for the given request is available a cached response.
*/
HttpCacheService.prototype.has = function (request) {
var key = this.getRequestIdentifier(request);
return this.prefixedStore.has(key);
};
/**
* Tells if the cached request is expired or not.
*/
HttpCacheService.prototype.isExpired = function (request) {
var cachedEntry = this.getEntry(request);
if (!cachedEntry) {
return true;
}
return this.isEntryExpired(cachedEntry);
};
/**
* Gets the cached entry in the map for the given request.
*/
HttpCacheService.prototype.get = function (request) {
var cachedEntry = this.getEntry(request);
if (!cachedEntry) {
return undefined;
}
var isExpired = this.isEntryExpired(cachedEntry);
return isExpired ? undefined : cachedEntry.response;
};
/**
* Puts a new cached response for the given request.
*/
HttpCacheService.prototype.put = function (request, response) {
var _this = this;
if (!request.maxAge) {
return;
}
var reqKey = this.getRequestIdentifier(request);
var entry = {
response: response,
identifier: reqKey,
cachedAt: new Date(),
maxAge: request.maxAge,
};
// Update the store.
this.prefixedStore.put(entry.identifier, entry);
// Remove the entry from the cache once expired.
var timerRef = setTimeout(function () {
_this.removeEntry(entry);
clearTimeout(timerRef);
}, request.maxAge);
};
/**
* Founds all expired entry and deletes them from the cache.
*/
HttpCacheService.prototype.prune = function () {
var _this = this;
var entries = this.prefixedStore.entries();
entries.forEach(function (entry) {
var isEntryExpired = _this.isEntryExpired(entry);
if (isEntryExpired) {
_this.removeEntry(entry);
}
});
};
/**
* Flush the cache by removing all entries.
*/
HttpCacheService.prototype.flush = function () {
this.prefixedStore.flush();
};
return HttpCacheService;
}());
export { HttpCacheService };