Skip to content

Cell - Cache Component with cache-manager ​

Named cache managers for Cell backends, on cache-manager 5.

bash
npm install @celljs/cache
ts
import { Autowired, Component, Named } from '@celljs/core';
import { CacheManager } from '@celljs/cache';

@Component()
export class UserService {
    @Autowired(CacheManager)                 // the cache named "default"
    protected readonly cache: CacheManager;

    @Autowired(CacheManager) @Named('sessions')
    protected readonly sessions: CacheManager;

    getUser(id: string) {
        return this.cache.wrap(`user:${id}`, () => this.load(id), 60_000);   // computed once, kept 60 s
    }
}

CacheManager has get, set(key, value, ttl?), del, reset and wrap(key, fn, ttl?). A manager is created the first time it is injected.

Configuration (cache.config) ​

One entry per cache name:

yaml
cache:
  config:
    default:
      store: memory
      max: 100            # entries
      ttl: 3600000        # milliseconds
    sessions:
      store: redis-yet    # needs the cache-manager-redis-yet package
      url: "${env.REDIS_URL}"
      ttl: 86400000
  • ttl is in milliseconds, as in cache-manager 5. The default cache keeps entries 3600 ms.
  • store is memory or the name of a store package you install: redis (cache-manager-redis), redis-store, redis-yet, ioredis, ioredis-yet, mongodb, mongoose, fs-binary, fs-hash, hazelcast, memcached-store, memory-store (each cache-manager-<name>). The other keys are the options of that store.
  • A list of entries makes a multi-level cache (multiCaching): reads try each store in order.
  • Injecting a name without configuration throws Not found cache options.

Bind your own CacheStoreFactory (rebind: true) to create stores another way.