shora-ai-payment-sdk
Version:
The first open-source payment SDK designed specifically for AI agents and chatbots - ACP Compatible
91 lines (90 loc) • 2.48 kB
JavaScript
class MemoryCache {
constructor(options = {}) {
this.cache = new Map();
this.ttl = options.ttl || 300000;
this.maxSize = options.maxSize || 1000;
}
get(key) {
const item = this.cache.get(key);
if (!item) {
return undefined;
}
if (Date.now() > item.expires) {
this.cache.delete(key);
return undefined;
}
return item.value;
}
set(key, value, ttl) {
const now = Date.now();
const expires = now + (ttl || this.ttl);
if (this.cache.size >= this.maxSize) {
const oldestKey = this.cache.keys().next().value;
if (oldestKey) {
this.cache.delete(oldestKey);
}
}
this.cache.set(key, {
value,
expires,
created: now
});
}
delete(key) {
return this.cache.delete(key);
}
clear() {
this.cache.clear();
}
size() {
return this.cache.size;
}
cleanup() {
const now = Date.now();
for (const [key, item] of this.cache.entries()) {
if (now > item.expires) {
this.cache.delete(key);
}
}
}
}
class CacheManager {
constructor() {
this.caches = new Map();
}
getCache(name, options) {
if (!this.caches.has(name)) {
this.caches.set(name, new MemoryCache(options));
}
return this.caches.get(name);
}
clearCache(name) {
this.caches.delete(name);
}
clearAllCaches() {
this.caches.clear();
}
cleanupAllCaches() {
for (const cache of this.caches.values()) {
cache.cleanup();
}
}
}
export const cacheManager = new CacheManager();
export function cached(ttl = 300000, cacheName = 'default') {
return function (target, propertyName, descriptor) {
const method = descriptor.value;
const cache = cacheManager.getCache(cacheName, { ttl });
descriptor.value = async function (...args) {
const cacheKey = `${propertyName}:${JSON.stringify(args)}`;
const cached = cache.get(cacheKey);
if (cached !== undefined) {
return cached;
}
const result = await method.apply(this, args);
cache.set(cacheKey, result, ttl);
return result;
};
};
}
export { MemoryCache, CacheManager };