@duongtrungnguyen/next-helper
Version:
Helper library for Next.js 15
99 lines • 2.57 kB
JavaScript
class QueryCache {
constructor() {
this.cache = /* @__PURE__ */ new Map();
}
getKeyString(queryKey) {
return JSON.stringify(queryKey);
}
get(queryKey) {
const keyString = this.getKeyString(queryKey);
const entry = this.cache.get(keyString);
if (!entry) {
return void 0;
}
if (this.isStale(queryKey)) {
this.cache.delete(keyString);
return void 0;
}
return entry.data;
}
set(queryKey, data, staleTime = 5 * 60 * 1e3, cacheTime = 30 * 60 * 1e3) {
const keyString = this.getKeyString(queryKey);
const entry = this.cache.get(keyString);
if (entry) {
entry.data = data;
entry.timestamp = Date.now();
entry.staleTime = staleTime;
entry.cacheTime = cacheTime;
entry.subscribers.forEach((callback) => callback());
} else {
this.cache.set(keyString, {
data,
timestamp: Date.now(),
staleTime,
cacheTime,
subscribers: /* @__PURE__ */ new Set()
});
}
}
isStale(queryKey) {
const keyString = this.getKeyString(queryKey);
const entry = this.cache.get(keyString);
if (!entry) {
return true;
}
const now = Date.now();
return now - entry.timestamp > entry.staleTime;
}
subscribe(queryKey, callback) {
const keyString = this.getKeyString(queryKey);
let entry = this.cache.get(keyString);
if (!entry) {
entry = {
data: void 0,
timestamp: 0,
staleTime: 0,
cacheTime: 0,
subscribers: /* @__PURE__ */ new Set()
};
this.cache.set(keyString, entry);
}
entry.subscribers.add(callback);
return () => {
const currentEntry = this.cache.get(keyString);
if (currentEntry) {
currentEntry.subscribers.delete(callback);
}
};
}
invalidate(queryKey) {
const keyString = this.getKeyString(queryKey);
const entry = this.cache.get(keyString);
if (entry) {
entry.timestamp = 0;
entry.subscribers.forEach((callback) => callback());
}
}
remove(queryKey) {
const keyString = this.getKeyString(queryKey);
this.cache.delete(keyString);
}
clear() {
this.cache.clear();
}
getMatchingKeys(queryKey) {
const prefix = this.getKeyString(queryKey);
const matchingKeys = [];
this.cache.forEach((_, key) => {
if (key.startsWith(prefix)) {
matchingKeys.push(JSON.parse(key));
}
});
return matchingKeys;
}
}
const queryCache = new QueryCache();
export {
queryCache
};
//# sourceMappingURL=cache.js.map