Skip to content

Cache

Contract

@modularityjs/cache defines the abstract CacheService:

typescript
abstract class CacheService {
  abstract get<T>(key: string): Promise<T | undefined>;
  abstract set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
  abstract delete(key: string): Promise<void>;
  abstract has(key: string): Promise<boolean>;
}

Drivers

Memory (@modularityjs/cache-memory)

Map-based in-memory cache with TTL support and LRU eviction. For development and testing.

typescript
import { CacheModule } from '@modularityjs/core';
import { CacheMemoryModule } from '@modularityjs/cache-memory';

const modules = [
  CacheModule,
  CacheMemoryModule,
  // or with config:
  CacheMemoryModule.forRoot({ maxSize: 5000 }),
];

Redis (@modularityjs/cache-redis)

Redis-backed cache with JSON serialization. Requires @modularityjs/redis.

typescript
import { CacheModule } from '@modularityjs/core';
import { CacheRedisModule } from '@modularityjs/cache-redis';
import { RedisModule } from '@modularityjs/redis';

const modules = [
  RedisModule.forRoot({ host: 'localhost', port: 6379 }),
  CacheModule,
  CacheRedisModule,
  // or with config:
  CacheRedisModule.forRoot({ defaultTtlMs: 60_000 }),
];

Usage

typescript
import { Inject, Injectable, CacheService } from '@modularityjs/core';

@Injectable()
class UserService {
  constructor(@Inject(CacheService) private readonly cache: CacheService) {}

  async getUser(id: string): Promise<User> {
    const cached = await this.cache.get<User>(`user:${id}`);
    if (cached) return cached;

    const user = await this.fetchFromDb(id);
    await this.cache.set(`user:${id}`, user, 300_000); // 5 min TTL
    return user;
  }
}