Plugins
Garbage Collection
Automatically clean up old cache entries to prevent memory leaks
Installation
bash npm install @spoosh/plugin-gc bash pnpm add @spoosh/plugin-gc bash yarn add @spoosh/plugin-gc bash bun add @spoosh/plugin-gc Usage
import { Spoosh } from "@spoosh/core";
import { cachePlugin } from "@spoosh/plugin-cache";
import { gcPlugin } from "@spoosh/plugin-gc";
const spoosh = new Spoosh<ApiSchema, Error>("/api").use([
cachePlugin({ staleTime: 5000 }),
gcPlugin({
maxAge: 30 * 60 * 1000, // Remove entries older than 30 minutes
maxEntries: 100, // Keep max 100 entries
interval: 60 * 1000, // Run GC every minute
}),
]);Options
| Option | Type | Default | Description |
|---|---|---|---|
maxAge | number | undefined | Maximum age in milliseconds. Entries older than this will be removed. |
maxEntries | number | undefined | Maximum number of cache entries. Oldest entries are removed when exceeded. |
interval | number | 60000 | Interval in milliseconds between GC runs. |
Instance API
The plugin exposes a manual trigger function on the Spoosh instance:
const { runGc } = createAngularSpoosh(api);
// Manually trigger garbage collection
const removedCount = runGc();Examples
Time-based cleanup only
Remove cache entries that haven't been updated in 10 minutes:
gcPlugin({
maxAge: 10 * 60 * 1000,
});Size-based cleanup only
Keep only the 50 most recent entries:
gcPlugin({
maxEntries: 50,
});Combined cleanup
Use both time and size limits for optimal memory management:
gcPlugin({
maxAge: 30 * 60 * 1000, // 30 minutes
maxEntries: 100,
interval: 5 * 60 * 1000, // Check every 5 minutes
});Aggressive cleanup for mobile
More frequent cleanup with lower limits for memory-constrained devices:
gcPlugin({
maxAge: 5 * 60 * 1000, // 5 minutes
maxEntries: 20,
interval: 30 * 1000, // Every 30 seconds
});How It Works
- Time-based cleanup: Entries with
timestampolder thanmaxAgeare removed first - Size-based cleanup: If cache still exceeds
maxEntries, oldest entries (by timestamp) are removed - Interval execution: GC runs automatically at the specified interval
- Manual trigger: Use
runGc()to trigger cleanup on demand
Best Practices
- Always use with
cachePlugin- GC cleans up the same cache thatcachePluginmanages - Set
maxAgeslightly higher than your longeststaleTimeto avoid removing useful cache - Monitor
runGc()return value in development to tune your settings