UNPKG

@nhan2804/nestjs-cacheable

Version:

@nestjs/cacheable is a flexible caching library for NestJS that leverages Redis for efficient and scalable storage. With support for function-level caching through easy-to-use decorators, it allows developers to seamlessly enhance performance while mainta

54 lines (50 loc) 1.44 kB
import { DynamicModule, Global, Inject, Module, OnModuleInit, Provider, } from "@nestjs/common"; import { Cache } from "cache-manager"; import { CACHE_MANAGER } from "@nestjs/cache-manager"; import { setCacheConfiguration, setCacheManager } from "./cacheable.helpers"; import { CacheableConfiguration } from "./cacheable.interfaces"; const CACHEABLE_CONFIG = "CACHEABLE_CONFIG"; @Global() @Module({}) export class CacheableModule implements OnModuleInit { constructor( @Inject(CACHE_MANAGER) cacheManager: Cache, @Inject(CACHEABLE_CONFIG) private readonly config: CacheableConfiguration ) { setCacheManager(cacheManager); //get current provider } onModuleInit() { // Now that everything is initialized, you can safely use your providers setCacheConfiguration(this.config); console.log(this.config); // Cache manager provider } static forRootAsync(options: { imports: any[]; useFactory: ( ...args: any[] ) => Promise<CacheableConfiguration> | CacheableConfiguration; inject: any[]; }): DynamicModule { const providers: Provider[] = [ { provide: CACHEABLE_CONFIG, useFactory: options.useFactory, inject: options.inject, }, ]; return { module: CacheableModule, imports: options.imports, providers: providers, exports: providers, }; } }