@truxie/cache
v0.1.2
Published
Caching for truxie — @Cacheable / @CacheEvict decorators and an injectable CacheManager over a pluggable store
Maintainers
Readme
@truxie/cache
Caching for truxie: @Cacheable / @CacheEvict decorators and an injectable CacheManager, over a store you can replace.
npm install @truxie/cache@Module({imports: [CacheModule.forRoot({ttl: 300, max: 1000})]})
export class AppModule {}
@Injectable()
class ProductService {
@Cacheable({key: 'product:{0}', ttl: 300})
async findById(id: string) { … }
@CacheEvict({key: 'product:{0}'})
async update(id: string, data: unknown) { … }
}The store is a port, not a setting
CacheManager is injected with CACHE_STORE and knows nothing else — not that a memory store exists, and certainly not how to build one. Replacing the implementation is a provider change, and the manager is unchanged and untouched by it.
// An instance you built yourself
CacheModule.forRoot({store: new RedisCacheStore(client)})
// A store that needs its own injected dependencies
CacheModule.forRootAsync({
imports: [RedisModule],
inject: [RedisClient],
useFactory: (redis: RedisClient) => ({store: new RedisCacheStore(redis), ttl: 60}),
})CacheStore is four methods — get, set, del, clear. Anything satisfying them is a valid store.
A cache failure is not a request failure
Every operation is wrapped: a store that throws is reported to onError and treated as a miss. A cache is an optimisation, and losing it must not lose the request. This is the one place where swallowing an error is the correct behaviour rather than a smell — which is why it is confined to the manager and never to the store.
Options
| Option | Default | |
|---|---|---|
| store | MemoryStore | Any CacheStore. |
| ttl | 0 (no expiry) | Default lifetime in seconds. |
| max | 0 (unlimited) | Entry ceiling for the built-in memory store. |
| onError | console.error | Called when a store operation throws. |
MemoryStore is per-process: behind more than one instance each gets its own cache, and they will disagree. Use a shared store when that matters.
