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/recipes/async-local-storage.md
+33-30Lines changed: 33 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,9 @@
4
4
5
5
The main idea of Async Local Storage is that we can _wrap_ some function call with the `AsyncLocalStorage#run` call. All code that is invoked within the wrapped call gets access to the same `store`, which will be unique to each call chain.
6
6
7
-
In the context of NestJS, that means if we can find a place within the request's lifecycle where we can wrap the rest of the request's code, we will be able to access and modify state visible only to that request, effectively eliminating the need for REQUEST scoped providers and their limitations.
7
+
In the context of NestJS, that means if we can find a place within the request's lifecycle where we can wrap the rest of the request's code, we will be able to access and modify state visible only to that request, which may serve as an alternative to REQUEST-scoped providers and some of their limitations.
8
+
9
+
Alternatively, we can use ALS to propagate context for only a part of the system (for example the _transaction_ object) without passing it around explicitly across services, which can increase isolation and encapsulation.
8
10
9
11
#### Custom implementation
10
12
@@ -17,9 +19,6 @@ NestJS itself does not provide any built-in abstraction for `AsyncLocalStorage`,
17
19
```ts
18
20
/** als.module.ts */
19
21
20
-
import { AsyncLocalStorage } from'async_hooks';
21
-
import { Module } from'@nestjs/core';
22
-
23
22
@Module({
24
23
providers: [
25
24
{
@@ -31,37 +30,41 @@ import { Module } from '@nestjs/core';
31
30
})
32
31
exportclassAlsModule {}
33
32
```
33
+
> info **Hint**`AsyncLocalStorage` is imported from `async_hooks`.
34
34
35
35
2. We're only concerned with HTTP, so let's use a middleware to wrap the `next` function with `AsyncLocalStorage#run`. Since a middleware is the first thing that the request hits, this will make the `store` available in all enhancers and the rest of the system.
0 commit comments