Advanced Features
These examples showcase advanced features like expiration, batch operations, compression, and cross-tab synchronization.
Automatic Expiration
Section titled “Automatic Expiration”Store temporary data that expires after a set duration.
const storage = new StorageManager(false, { namespace: 'tempData', defaultExpiration: { session: 60, // Sessions expire in 60 seconds }, enableCompression: false});
// Store a temporary sessionasync function createSession() { await storage.set('session', { token: 'abc123', user: 'Alice', timestamp: Date.now() });
console.log('Session created, expires in 60 seconds'); checkSession();}
// Check if session is still validasync function checkSession() { const hasSession = await storage.has('session'); const session = await storage.get('session');
document.getElementById('status').textContent = hasSession ? `Active: ${session.user}` : 'Expired';}
// Check every secondsetInterval(checkSession, 1000);Batch Operations
Section titled “Batch Operations”Efficiently handle multiple items at once.
const storage = new StorageManager(false, { namespace: 'batchDemo', enableCompression: false});
// Initialize with batch setasync function initialize() { await storage.batchSet([ { key: 'user1', value: { name: 'Alice', role: 'admin' } }, { key: 'user2', value: { name: 'Bob', role: 'user' } }, { key: 'user3', value: { name: 'Charlie', role: 'user' } }, { key: 'settings', value: { theme: 'dark', lang: 'en' } } ]);
console.log('Batch set complete'); displayData();}
// Retrieve multiple itemsasync function displayData() { const data = await storage.batchGet([ 'user1', 'user2', 'user3', 'settings' ]);
const output = document.getElementById('output'); output.innerHTML = Object.entries(data) .map(([key, value]) => `<div><strong>${key}:</strong> ${JSON.stringify(value, null, 2)}</div>` ) .join('');}
// Remove multiple itemsasync function cleanup() { await storage.batchRemove(['user1', 'user2', 'user3']); console.log('Users removed'); displayData();}Shopping Cart with Expiration
Section titled “Shopping Cart with Expiration”A complete shopping cart that expires after 30 minutes of inactivity.
const storage = new StorageManager(false, { namespace: 'shop', defaultExpiration: { cart: 1800 // 30 minutes }, enableCompression: true});
// Add item to cartasync function addToCart(item) { let cart = await storage.get('cart') || [];
const existing = cart.find(i => i.id === item.id); if (existing) { existing.quantity++; } else { cart.push({ ...item, quantity: 1 }); }
await storage.set('cart', cart); displayCart();}
// Display cartasync function displayCart() { const cart = await storage.get('cart') || []; const cartEl = document.getElementById('cart');
if (cart.length === 0) { cartEl.innerHTML = '<p>Cart is empty</p>'; return; }
const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0 );
cartEl.innerHTML = cart.map(item => \`<div>\${item.name} x\${item.quantity} - $\${(item.price * item.quantity).toFixed(2)}</div>\` ).join('') + \`<div><strong>Total: $\${total.toFixed(2)}</strong></div>\`;}
// Sample productsconst products = [ { id: 1, name: 'Widget', price: 9.99 }, { id: 2, name: 'Gadget', price: 19.99 }, { id: 3, name: 'Doohickey', price: 14.99 }];Cross-Tab Synchronization
Section titled “Cross-Tab Synchronization”Open this example in multiple tabs to see real-time synchronization.
const storage = new StorageManager(false, { namespace: 'multiTab', enableCompression: false});
// Initializelet currentUser = await storage.get('currentUser') || null;updateDisplay();
// Listen for changes from other tabsstorage.onChange('currentUser', (newUser) => { currentUser = newUser; updateDisplay(); showNotification('User updated in another tab!');});
// Loginasync function login(username) { currentUser = { username, loginTime: new Date().toISOString() }; await storage.set('currentUser', currentUser); updateDisplay();}
// Logoutasync function logout() { currentUser = null; await storage.remove('currentUser'); updateDisplay();}
function updateDisplay() { const display = document.getElementById('userDisplay'); if (currentUser) { display.innerHTML = \`Logged in as: <strong>\${currentUser.username}</strong>\`; } else { display.innerHTML = 'Not logged in'; }}Best Practices
Section titled “Best Practices”When building advanced applications with StorageManager.js:
- Use namespaces to avoid key collisions between features
- Set appropriate expirations for temporary data
- Use batch operations when working with multiple items
- Enable compression for large objects to save space
- Clean up listeners when components unmount
- Validate data retrieved from storage before using it
- Handle null values gracefully (expired or missing keys)
Next Steps
Section titled “Next Steps”You’ve now seen the full power of StorageManager.js! For detailed API documentation, visit the API Reference.