Skip to content

Instantly share code, notes, and snippets.

@Maxiviper117
Last active March 10, 2025 10:50
Show Gist options
  • Save Maxiviper117/54210cb7a70fe314203be1813f92f87f to your computer and use it in GitHub Desktop.
Save Maxiviper117/54210cb7a70fe314203be1813f92f87f to your computer and use it in GitHub Desktop.
Simple Cache Class Usage Guide for Node.js

Cache Class with Automatic Cleanup

This guide demonstrates how to use an updated Cache class in your Node.js or TypeScript projects. The class includes a Time-to-Live (TTL) mechanism for cache entries, automatic cleanup of expired items, and a method to stop the cleanup process when needed.

1. Cache Class Code

Copy the following code into a file (e.g., Cache.ts):

export class Cache<T> {
	private store: Map<string, { timestamp: number; value: T }>;
	private ttl: number;
	private cleanupInterval: NodeJS.Timeout;

	/**
	 * @param ttl Time to live in milliseconds.
	 * @param cleanupIntervalMs How frequently to run cleanup (optional, default 1 minute).
	 */
	constructor(ttl: number, cleanupIntervalMs: number = 60000) {
		this.store = new Map();
		this.ttl = ttl;
		this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs);
	}

	get(key: string): T | null {
		const cached = this.store.get(key);
		if (!cached) return null;

		if (Date.now() - cached.timestamp >= this.ttl) {
			this.store.delete(key);
			return null;
		}

		return cached.value;
	}

	set(key: string, value: T): void {
		this.store.set(key, { timestamp: Date.now(), value });
	}

	delete(key: string): void {
		this.store.delete(key);
	}

	clear(): void {
		this.store.clear();
	}

	private cleanup() {
		const now = Date.now();
		for (const [key, { timestamp }] of this.store.entries()) {
			if (now - timestamp >= this.ttl) {
				this.store.delete(key);
			}
		}
	}

	// Optionally, add a method to stop cleanup if needed.
	stopCleanup() {
		clearInterval(this.cleanupInterval);
	}
}

2. Importing and Instantiating the Cache

In another file (e.g., app.ts), import the class and create an instance. In this example, we set up a cache with a TTL of 5 seconds (5000 milliseconds) and let the cleanup run every minute:

import { Cache } from './Cache';

const myCache = new Cache<string>(5000); // Cache that holds strings with a TTL of 5000ms

3. Setting and Retrieving Cached Data

Setting a Value

Use the set method to store a value with a specific key:

myCache.set('greeting', 'Hello, world!');
console.log('Value set in cache.');

Retrieving a Value

Use the get method to retrieve a value. If the TTL has expired or the key doesn’t exist, it returns null:

const greeting = myCache.get('greeting');

if (greeting) {
  console.log('Cached value:', greeting);
} else {
  console.log('Cache miss or expired.');
}

4. Deleting and Clearing the Cache

Deleting a Specific Key

Remove a specific entry using the delete method:

myCache.delete('greeting');
console.log('Value deleted from cache.');

Clearing All Cache

To remove all entries, use the clear method:

myCache.clear();
console.log('All cache cleared.');

5. Stopping the Automatic Cleanup

If you need to stop the automatic cleanup (for example, before shutting down your application), use the stopCleanup method:

myCache.stopCleanup();
console.log('Automatic cleanup stopped.');

6. Full Example

Below is a complete example combining all of the steps above:

import { Cache } from './Cache';

// Create a cache with a 5-second TTL and cleanup running every minute
const myCache = new Cache<string>(5000);

// Set a value
myCache.set('greeting', 'Hello, world!');
console.log('Value set in cache.');

// Retrieve the value immediately
let greeting = myCache.get('greeting');
console.log('Immediately retrieved:', greeting);

// Wait for 6 seconds to let the value expire
setTimeout(() => {
  greeting = myCache.get('greeting');
  if (greeting) {
    console.log('After timeout, cached value:', greeting);
  } else {
    console.log('After timeout, cache miss or expired.');
  }
  
  // Optionally, stop the cleanup interval
  myCache.stopCleanup();
  console.log('Automatic cleanup stopped.');
}, 6000);

7. Summary

  • Import the Cache: Include the updated Cache class in your project.
  • Instantiate the Cache: Create an instance with a defined TTL and optional cleanup interval.
  • Set and Get Data: Use set to cache data and get to retrieve it.
  • Manage Cache: Use delete for individual keys, clear to empty the cache, and stopCleanup to halt the automatic cleanup process.

Happy coding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment