Caching is a great and simple technique that helps improve your app's performance. It acts as a temporary data store providing high performance data access.
First install required packages:
Nest provides a unified API for various cache storage providers. The built-in one is an in-memory data store. However, you can easily switch to a more comprehensive solution, like Redis.
In order to enable caching, import the
CacheModule and call its
To interact with the cache manager instance, inject it to your class using the
CACHE_MANAGER token, as follows:
info Hint The
Cacheclass is imported from the
CACHE_MANAGERtoken from the
get method on the
Cache instance (from the
cache-manager package) is used to retrieve items from the cache. If the item does not exist in the cache, an exception will be thrown.
To add an item to the cache, use the
The default expiration time of the cache is 5 seconds.
You can manually specify a TTL (expiration time) for this specific key, as follows:
To disable expiration of the cache, set the
ttl configuration property to
To remove an item from the cache, use the
To clear the entire cache, use the
warning Warning In GraphQL applications, interceptors are executed separately for each field resolver. Thus,
CacheModule(which uses interceptors to cache responses) will not work properly.
To enable auto-caching responses, just tie the
CacheInterceptor where you want to cache data.
warningWarning Onlyresponse mapping for more details.
GETendpoints are cached. Also, HTTP server routes that inject the native response object (
@Res()) cannot use the Cache Interceptor. See
To reduce the amount of required boilerplate, you can bind
CacheInterceptor to all endpoints globally:
All cached data has its own expiration time (TTL). To customize default values, pass the options object to the
While global cache is enabled, cache entries are stored under a
CacheKey that is auto-generated based on the route path. You may override certain cache settings (
@CacheTTL()) on a per-method basis, allowing customized caching strategies for individual controller methods. This may be most relevant while using different cache stores.
info Hint The
@CacheTTL()decorators are imported from the
@CacheKey() decorator may be used with or without a corresponding
@CacheTTL() decorator and vice versa. One may choose to override only the
@CacheKey() or only the
@CacheTTL(). Settings that are not overridden with a decorator will use the default values as registered globally (see Customize caching).
You can also apply the
CacheInterceptor to WebSocket subscribers as well as Microservice's patterns (regardless of the transport method that is being used).
However, the additional
@CacheKey() decorator is required in order to specify a key used to subsequently store and retrieve cached data. Also, please note that you shouldn't cache everything. Actions which perform some business operations rather than simply querying the data should never be cached.
Additionally, you may specify a cache expiration time (TTL) by using the
@CacheTTL() decorator, which will override the global default TTL value.
info Hint The
@CacheTTL()decorator may be used with or without a corresponding
By default, Nest uses the request URL (in an HTTP app) or cache key (in websockets and microservices apps, set through the
@CacheKey() decorator) to associate cache records with your endpoints. Nevertheless, sometimes you might want to set up tracking based on different factors, for example, using HTTP headers (e.g.
Authorization to properly identify
In order to accomplish that, create a subclass of
CacheInterceptor and override the
This service takes advantage of cache-manager under the hood. The
cache-manager package supports a wide-range of useful stores, for example, Redis store. A full list of supported stores is available here. To set up the Redis store, simply pass the package together with corresponding options to the
You may want to asynchronously pass in module options instead of passing them statically at compile time. In this case, use the
registerAsync() method, which provides several ways to deal with async configuration.
One approach is to use a factory function:
Our factory behaves like all other asynchronous module factories (it can be
async and is able to inject dependencies through
Alternatively, you can use the
The above construction will instantiate
CacheModule and will use it to get the options object. The
CacheConfigService has to implement the
CacheOptionsFactory interface in order to provide the configuration options:
If you wish to use an existing configuration provider imported from a different module, use the
This works the same as
useClass with one critical difference -
CacheModule will lookup imported modules to reuse any already-created
ConfigService, instead of instantiating its own.
A working example is available here.