globalping-ts
Version:
Typescript library for the Globalping API
65 lines (64 loc) • 1.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
const crypto_1 = __importDefault(require("crypto"));
class Cache {
constructor(maxCacheSize) {
this.maxCacheSize = 200;
this.cache = new Map();
this.maxCacheSize = maxCacheSize;
}
get(key) {
return this.cache.get(key);
}
generateCacheKey(endpoint, params) {
return crypto_1.default
.createHash('md5')
.update(`${endpoint}?${JSON.stringify(params)}`)
.digest('hex');
}
addToCache(key, entry) {
if (this.cache.size >= this.maxCacheSize) {
const oldestKey = this.findOldestCacheEntry();
if (oldestKey) {
this.cache.delete(oldestKey);
}
}
this.cache.set(key, entry);
}
updateCacheEntryTimestamp(key) {
const entry = this.cache.get(key);
if (entry) {
entry.timestamp = Date.now();
this.cache.set(key, entry);
}
}
findOldestCacheEntry() {
let oldestKey = null;
let oldestTimestamp = Infinity;
for (const [key, entry] of this.cache.entries()) {
if (entry.timestamp < oldestTimestamp) {
oldestTimestamp = entry.timestamp;
oldestKey = key;
}
}
return oldestKey;
}
clearCache() {
this.cache.clear();
}
getCacheSize() {
return this.cache.size;
}
removeCacheEntry(endpoint, params) {
const key = this.generateCacheKey(endpoint, params);
return this.cache.delete(key);
}
getCachedKeys() {
return Array.from(this.cache.keys());
}
}
exports.Cache = Cache;