@foundatiofx/fetchclient
Version:
A typed JSON fetch client with middleware support for Deno, Node and the browser.
89 lines (88 loc) • 2.66 kB
JavaScript
/**
* Represents a cache for storing responses from the FetchClient.
*/
export class FetchClientCache {
cache = new Map();
/**
* Sets a response in the cache with the specified key.
* @param key - The cache key.
* @param response - The response to be cached.
* @param cacheDuration - The duration for which the response should be cached (in milliseconds).
*/
set(key, response, cacheDuration) {
this.cache.set(this.getHash(key), {
key,
lastAccess: new Date(),
expires: new Date(Date.now() + (cacheDuration ?? 60000)),
response,
});
}
/**
* Retrieves a response from the cache with the specified key.
* @param key - The cache key.
* @returns The cached response, or null if the response is not found or has expired.
*/
get(key) {
const cacheEntry = this.cache.get(this.getHash(key));
if (!cacheEntry) {
return null;
}
if (cacheEntry.expires < new Date()) {
this.cache.delete(this.getHash(key));
return null;
}
cacheEntry.lastAccess = new Date();
return cacheEntry.response;
}
/**
* Deletes a response from the cache with the specified key.
* @param key - The cache key.
* @returns True if the response was successfully deleted, false otherwise.
*/
delete(key) {
return this.cache.delete(this.getHash(key));
}
/**
* Deletes all responses from the cache that have keys beginning with the specified key.
* @param prefix - The cache key prefix.
* @returns The number of responses that were deleted.
*/
deleteAll(prefix) {
let count = 0;
for (const key of this.cache.keys()) {
if (key.startsWith(this.getHash(prefix))) {
if (this.cache.delete(key)) {
count++;
}
}
}
return count;
}
/**
* Checks if a response exists in the cache with the specified key.
* @param key - The cache key.
* @returns True if the response exists in the cache, false otherwise.
*/
has(key) {
return this.cache.has(this.getHash(key));
}
/**
* Returns an iterator for the cache entries.
* @returns An iterator for the cache entries.
*/
values() {
return this.cache.values();
}
/**
* Clears all entries from the cache.
*/
clear() {
this.cache.clear();
}
getHash(key) {
if (key instanceof Array) {
return key.join(":");
}
return key;
}
}