Skip to main content

Caching

The CacheModule provided by Nest.js is actually a simple wrapper for the node-cache-manager. 1

Mutiple Individual caches

In terms of the implementation of CacheModule, it is not designed with multi-instance usage. For example, if you need a data cache that connects to Redis and a file cache that adapts to the file system, there is no way to get cache instances for different connections if you follow the official documentation.

But actually there is a way to do it. you can declare two additional modules: DataCacheModule and FileCacheModule and import the CacheModule inside it, then re-export Cache under a different token (so there are no conflicts, you inject Cache instance with different token).

NamedCacheModule

According to above, Nest.js Extends Toolkit provide a NamedCacheModule, it's a simple wrapper for CacheModule with an additional method parameter name, this parameter is used to specify the token of the re-exported cache instance.

import { Module, Inject, Injectable } from '@nestjs/common';
import { NamedCacheModule } from 'nestjs-extends';

const CUSTOM_CACHE_MANAGER = Symbol("CUSTOM_CACHE_MANAGER");

@Module({
imports: [
NamedCacheModule.registerAsync(CUSTOM_CACHE_MANAGER, {
useFactory: () => {
return {
max: 100,
ttl: 10 * 1000,
}
},
}),
]
})
class CustomCacheModule {}

@Injectable()
export class AppService {

@Inject(CUSTOM_CACHE_MANAGER) private readonly cache!: Cache;

}