You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/techniques/caching.md
+65-22Lines changed: 65 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,15 +4,18 @@ Caching is a great and simple **technique** that helps improve your app's perfor
4
4
5
5
#### Installation
6
6
7
-
First install the required package:
7
+
First install required packages:
8
8
9
9
```bash
10
-
$ npm install --save cache-manager
10
+
$ npm install cache-manager
11
+
$ npm install -D @types/cache-manager
11
12
```
12
13
13
14
#### In-memory cache
14
15
15
-
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, first import the `CacheModule` and call its `register()` method.
16
+
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.
17
+
18
+
In order to enable caching, import the `CacheModule` and call its `register()` method.
> info **Hint** The `Cache` class is imported from the `cache-manager`, while `CACHE_MANAGER` token from the `@nestjs/common` package.
40
+
41
+
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.
42
+
43
+
```typescript
44
+
const value =this.cacheManager.get('key');
45
+
```
46
+
47
+
To add an item to the cache, use the `set` method:
48
+
49
+
```typescript
50
+
awaitthis.cacheManager.set('key', 'value');
51
+
```
52
+
53
+
You can also specify a TTL (expiration time) for this specific key, as follows:
To remove an item from the cache, use the `del` method:
60
+
61
+
```typescript
62
+
awaitthis.cacheManager.del('key');
63
+
```
64
+
65
+
To clear the entire cache, use the `reset` method:
66
+
67
+
```typescript
68
+
awaitthis.cacheManager.reset();
69
+
```
70
+
71
+
#### Auto-caching responses
72
+
28
73
> warning **Warning** In [GraphQL](/graphql/quick-start) applications, interceptors are executed separately for each field resolver. Thus, `CacheModule` (which uses interceptors to cache responses) will not work properly.
29
74
30
-
Then just tie the `CacheInterceptor` where you want to cache data.
75
+
To enable auto-caching responses, just tie the `CacheInterceptor` where you want to cache data.
31
76
32
77
```typescript
33
78
@Controller()
@@ -43,8 +88,6 @@ export class AppController {
43
88
> warning**Warning** Only `GET` endpoints are cached. Also, HTTP server routes that inject the native response object (`@Res()`) cannot use the Cache Interceptor. See
44
89
> <ahref="https://docs.nestjs.com/interceptors#response-mapping">response mapping</a> for more details.
45
90
46
-
#### Global cache
47
-
48
91
To reduce the amount of required boilerplate, you can bind `CacheInterceptor` to all endpoints globally:
49
92
50
93
```typescript
@@ -139,6 +182,21 @@ handleEvent(client, data) {
139
182
140
183
> info **Hint** The `@CacheTTL()` decorator may be used with or without a corresponding `@CacheKey()` decorator.
141
184
185
+
#### Adjust tracking
186
+
187
+
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 `profile` endpoints).
188
+
189
+
In order to accomplish that, create a subclass of `CacheInterceptor` and override the `trackBy()` method.
190
+
191
+
```typescript
192
+
@Injectable()
193
+
class HttpCacheInterceptor extends CacheInterceptor {
This service takes advantage of [cache-manager](https://github.com/BryanDonovan/node-cache-manager) under the hood. The `cache-manager` package supports a wide-range of useful stores, for example, [Redis](https://github.com/dabroek/node-cache-manager-redis-store) store. A full list of supported stores is available [here](https://github.com/BryanDonovan/node-cache-manager#store-engines). To set up the Redis store, simply pass the package together with corresponding options to the `register()` method.
@@ -161,21 +219,6 @@ import { AppController } from './app.controller';
161
219
exportclassApplicationModule {}
162
220
```
163
221
164
-
#### Adjusttracking
165
-
166
-
Bydefault, NestusestherequestURL (inanHTTPapp) or cache key (inwebsocketsandmicroservicesapps, setthroughthe`@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`toproperlyidentify`profile`endpoints).
167
-
168
-
In order to accomplish that, create a subclass of `CacheInterceptor` and override the `trackBy()` method.
169
-
170
-
```typescript
171
-
@Injectable()
172
-
class HttpCacheInterceptor extends CacheInterceptor {
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.
@@ -196,7 +239,7 @@ Our factory behaves like all other asynchronous module factories (it can be `asy
0 commit comments