Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Cache Manager

Cache Manager is a lightweight and efficient library for managing redis caching in your applications.

Features

  • Simple API for adding, retrieving, and deleting cache entries.
  • Configurable expiration policies for cached items.
  • Supports redis
  • Lightweight and fast.

Requirements

  • Node.js 20.11 or newer
  • NestJS 11.2.1 or newer within the 11.x release line
  • Redis server (the client stays on Redis 4.x)

Validation

npm ci
npm run build
npm run test:types
npm test
npm run test:cov

Real Redis tests are separate and require a running disposable Redis instance:

REDIS_URL=redis://127.0.0.1:6379 npm run test:redis

The integration tests use a unique key prefix and remove only their own keys. They never flush the database.

Installation

Install the package using npm

npm i @nestixis/cache-manager

Usage

Here’s a quick example of how to use Cache Manager:

Module registration

@Module({
  imports: [
    CacheModule.registerAsync({
      isGlobal: true,
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        redis: {
          host: configService.get('REDIS_HOST') || 'localhost',
          port: +configService.get('REDIS_PORT') || 6379,
        },
        cachePrefix: 'cache:',
        defaultCacheTTL: 1000,
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

Manual interaction with CacheManager

export class Service {
  constructor(private readonly cacheManager: CacheManager) {}

  async add(): Promise<void> {
    //...
    await this.cacheManager.set('key', { value: 1 }, 1000);
  }

  async remove(): Promise<void> {
    //...
    await this.cacheManager.delete('key');
  }

  async get(): Promise<any> {
    const cached = await this.cacheManager.get('key');
    if (cached) return cached;
  }
}

Automatic response caching. There are two interceptors first

  • CacheInterceptor - saves response for time defined by ttl.

  • CacheRemoveInterceptor - removes cache, can be used on POST, DELETE, PUT, PATCH methods. It ensures that cache will be removed.

@Controller('site/:token')
@CacheTrackBy({
  prefix: 'site'
  ttl: 10000,
  by: [
    {
      by: 'param',
      name: 'token',
    }
  ]
})
export class SiteController {
  constructor(
    private readonly service: Service
  )

  @Get()
  @UseInterceptors(CacheInterceptor)
  async get(): Promise<any> {
    return this.service.get();
  }

  @Post()
  @UseInterceptors(CacheRemoveInterceptor)
  async add(): Promise<void> {
    await this.service.add();
  }

  @Delete()
  @UseInterceptors(CacheRemoveInterceptor)
  async remove(): Promise<void> {
    await this.service.remove();
  }
}

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages