@tradly/auth
Version:
Auth package for Tradly - handles authentication (email, phone, social login)
93 lines (92 loc) • 2.33 kB
JavaScript
;
/**
* Simple in-memory cache implementation
* Can be replaced with Redis or other cache solutions in the future
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.cache = void 0;
class Cache {
constructor() {
this.cache = new Map();
}
/**
* Get value from cache
*/
get(key) {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
// Check if entry has expired
const now = Date.now();
if (now - entry.timestamp > entry.ttl) {
this.cache.delete(key);
return null;
}
return entry.data;
}
/**
* Set value in cache
*/
set(key, data, ttl = 3600000) {
// Default TTL: 1 hour
this.cache.set(key, {
data,
timestamp: Date.now(),
ttl,
});
}
/**
* Delete value from cache
*/
delete(key) {
this.cache.delete(key);
}
/**
* Clear all cache
*/
clear() {
this.cache.clear();
}
/**
* Check if key exists and is valid
*/
has(key) {
const entry = this.cache.get(key);
if (!entry) {
return false;
}
// Check if entry has expired
const now = Date.now();
if (now - entry.timestamp > entry.ttl) {
this.cache.delete(key);
return false;
}
return true;
}
}
// Singleton instance
// Ensure cache is always available, even in server environments
let cacheInstance = null;
function getCacheInstance() {
if (!cacheInstance) {
cacheInstance = new Cache();
}
return cacheInstance;
}
// Export cache instance - ensure it's always initialized
// Use Object.defineProperty to ensure it's always available
const cache = getCacheInstance();
exports.cache = cache;
// Ensure cache is always available even if module is reloaded
if (typeof globalThis !== "undefined") {
// Store in globalThis for Next.js server component compatibility
const globalCacheKey = "__tradly_auth_cache__";
if (!globalThis[globalCacheKey]) {
globalThis[globalCacheKey] = cache;
}
else {
// Use existing cache if available
Object.assign(cache, globalThis[globalCacheKey]);
}
}