Skip to content

Cache

Cache<TEntity, TResult>(setKeyOrOptions, deleteKeysFn?, invalidateKeysFn?): MethodDecorator

Defined in: packages/ddd-core/persistence/decorators/cache.decorator.ts:148

Write-through cache decorator for a CommandRepository save method.

Provides declarative cache synchronization on mutating database operations:

  • Write-through update: When save() resolves with a non-nullish result, the result is cached under the key generated by setKey (after invalidating any secondary keys via invalidateKeys).
  • Cache eviction on delete: When save() resolves with null or undefined (e.g. entity deletion), all keys returned by deleteKeys are evicted from the cache.
  • Best-effort safety: Cache write and eviction operations swallow errors internally so that an already-committed database transaction is never converted into an application error.
  • Explicit keys: Requires at least one of setKey, deleteKeys or invalidateKeys; scoping the key (for example with cacheKey) is the key function’s job.

TEntity = unknown

TResult = unknown

CacheOptions<TEntity> | ((entity) => string) | null

((entity) => string[]) | null

((entity) => string[]) | null

MethodDecorator

Positional syntax on creation / update

@Cache<User, UserSnapshot>(
(user) => cacheKey(User.aggregateName, { id: user.id }),
null,
(user) => [cacheKey(User.aggregateName, { email: user.email })],
)
async save(user: User): Promise<UserSnapshot> { ... }

Cache maintenance runs only after the wrapped persistence method succeeds and is best-effort: cache failures are logged rather than converting an already durable write into an application failure. Pair this decorator with @AcknowledgePersisted and @MapPersistenceErrors in the canonical order.

Options object syntax on eviction / delete

@Cache<User, null>({
deleteKeys: (user) => [
cacheKey(User.aggregateName, { id: user.id }),
cacheKey(User.aggregateName, { email: user.email }),
],
})
async save(user: User): Promise<null> { ... }