Skip to content

API Reference

Sajidur edited this page Oct 26, 2024 · 1 revision

API Reference 📜

Welcome to the SnapCache API Reference! This section provides detailed information about the methods available in SnapCache, including their parameters and return values.

SnapCache Class

SnapCache(options)

Creates a new instance of SnapCache.

Parameters

  • options: An object to configure the cache.
    • maxSize (Number): The maximum number of items allowed in the cache. (Default: 100)
    • defaultTTL (Number): The default time-to-live for items in milliseconds. (Default: 60000)

Example

const cache = new SnapCache({ maxSize: 200, defaultTTL: 30000 });

Methods

cache.set(key, value, options)

Stores a value in the cache with the specified key.

Parameters

  • key (String): The unique key under which the value is stored.
  • value (Object): The value to cache (can be any object).
  • options (Object, optional): Configuration for this cache entry.
    • ttl (Number): The time-to-live for this entry in milliseconds. Overrides the default TTL.

Returns

  • undefined

Example

cache.set('user:456', { name: 'Bob' }, { ttl: 120000 }); // 2 minutes TTL

cache.get(key)

Retrieves a value from the cache by its key.

Parameters

  • key (String): The key of the cached value.

Returns

  • Object: The cached value if it exists and hasn't expired; otherwise, returns null.

Example

const user = cache.get('user:456');
console.log(user); // Output: { name: 'Bob' } or null (if expired)

cache.delete(key)

Deletes a specific item from the cache.

Parameters

  • key (String): The key of the cached value to delete.

Returns

  • Boolean: true if the item was successfully deleted; otherwise, returns false if the item didn't exist.

Example

const deleted = cache.delete('user:456');
console.log(deleted); // Output: true or false

cache.clear()

Clears all items from the cache.

Returns

  • undefined

Example

cache.clear(); // Clears the entire cache

cache.size()

Returns the current number of items in the cache.

Returns

  • Number: The current size of the cache.

Example

console.log(cache.size()); // Output: current number of items

Conclusion

The SnapCache API provides a straightforward way to manage in-memory caching in your Node.js applications. With easy-to-use methods for setting, getting, deleting, and clearing cache entries, SnapCache helps you enhance the performance and efficiency of your applications.

For more information, check out the Usage Guide for practical examples and use cases!

Clone this wiki locally