@shaaz1000/rn-storage
Version:
A comprehensive storage solution for React Native with encryption, caching, and offline sync
108 lines • 3.12 kB
JavaScript
;
// src/core/cacheManager.ts
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const storageManager_1 = __importDefault(require("./storageManager"));
class CacheManager {
constructor(config = {}) {
this.storage = storageManager_1.default.getInstance();
this.config = {
expiryTime: 1000 * 60 * 60,
maxSize: 100,
encryptData: false,
...config
};
}
/**
* Get CacheManager instance
*/
static getInstance(config) {
if (!CacheManager.instance) {
CacheManager.instance = new CacheManager(config);
}
return CacheManager.instance;
}
/**
* Update cache configuration
* @param newConfig - New configuration options
*/
updateConfig(newConfig) {
this.config = {
...this.config,
...newConfig
};
}
/**
* Set cache item
* @param key - Cache key
* @param value - Value to cache
* @param customExpiryTime - Optional custom expiry time
*/
async set(key, value, customExpiryTime) {
const keys = await this.storage.getAllKeys();
// Check cache size limit
if (keys.length >= (this.config.maxSize || 100) && !(await this.storage.hasKey(key))) {
// Remove oldest item if cache is full
const oldestKey = await this.findOldestKey();
if (oldestKey) {
await this.storage.removeItem(oldestKey);
}
}
await this.storage.setItem(key, value, this.config.encryptData || false, customExpiryTime || this.config.expiryTime);
}
/**
* Get cache item
* @param key - Cache key
*/
async get(key) {
return await this.storage.getItem(key, this.config.encryptData || false);
}
/**
* Remove cache item
* @param key - Cache key
*/
async remove(key) {
await this.storage.removeItem(key);
}
/**
* Clear all cache
*/
async clear() {
await this.storage.clear();
}
/**
* Find oldest cache item
*/
async findOldestKey() {
const keys = await this.storage.getAllKeys();
if (keys.length === 0)
return null;
let oldestKey = keys[0];
let oldestTime = Date.now();
for (const key of keys) {
const item = await this.storage.getItem(key);
if (item && item.timestamp < oldestTime) {
oldestTime = item.timestamp;
oldestKey = key;
}
}
return oldestKey;
}
/**
* Get current cache size
*/
async getCacheSize() {
const keys = await this.storage.getAllKeys();
return keys.length;
}
/**
* Check if key exists in cache
*/
async has(key) {
return await this.storage.hasKey(key);
}
}
exports.default = CacheManager;
//# sourceMappingURL=cacheManager.js.map