-
Notifications
You must be signed in to change notification settings - Fork 1
Usage Guide
Welcome to the SnapCache Usage Guide! This section will help you understand how to use SnapCache in your Node.js applications. You'll find examples ranging from basic setup to advanced usage scenarios.
To begin using SnapCache, you first need to create an instance. Here's a simple example:
const SnapCache = require('snapcache');
// Create a SnapCache instance with default configurations
const cache = new SnapCache({ maxSize: 100, defaultTTL: 30000 }); // Default TTL of 30 secondsYou can store and retrieve values in the cache easily. Here’s how:
// Store a value in the cache with a specific TTL
cache.set('user:123', { name: 'Alice' }, { ttl: 60000 }); // 1 minute TTL
// Retrieve the value
const value = cache.get('user:123');
console.log(value); // Output: { name: 'Alice' }SnapCache automatically handles expiration based on the TTL you set. Here’s an example of how it works:
// Wait for the TTL to expire
setTimeout(() => {
console.log(cache.get('user:123')); // Output: null (expired)
}, 61000); // Wait 61 secondsYou can customize the maximum size of the cache and the default TTL for items:
// Create a new cache with a max size of 50 and default TTL of 10 seconds
const cache = new SnapCache({ maxSize: 50, defaultTTL: 10000 }); // Default TTL of 10 seconds
// Set values with different TTLs
cache.set('item1', { data: 'Sample Data 1' }, { ttl: 5000 }); // 5 seconds TTL
cache.set('item2', { data: 'Sample Data 2' }); // Uses default TTL of 10 seconds
// Wait and check the cache
setTimeout(() => {
console.log(cache.get('item1')); // Output: null (expired)
console.log(cache.get('item2')); // Output: { data: 'Sample Data 2' }
}, 6000);Managing the cache is easy with SnapCache. You can delete specific items or clear the entire cache:
// Delete a specific item
cache.delete('item2');
console.log(cache.get('item2')); // Output: null (deleted)
// Clear all items from the cache
cache.clear();
console.log(cache.get('item1')); // Output: null (cleared)When the cache exceeds the maximum size, SnapCache automatically evicts the oldest items to make space for new entries:
// Fill the cache beyond its limit
for (let i = 0; i < 55; i++) {
cache.set(`item:${i}`, { data: `Sample Data ${i}` });
}
// Check the size and contents of the cache
console.log(cache.size); // Output: 50 (max size)
console.log(cache.get('item:0')); // Output: null (evicted)With SnapCache, you can efficiently manage your in-memory cache with simple commands and configurations. Whether you need basic caching or advanced features, SnapCache is designed to help improve the performance of your Node.js applications.
Explore the API Reference for detailed information on all available methods and options in SnapCache.
📄 License: MIT License
📞 Support: If you have any questions or need assistance, feel free to reach out on our Discord.