1 | # A cls session implementation using async_hooks
|
2 |
|
3 | Continuation Local Storage works like thread-local storage in threaded programming. This is a implementation of CLS using async_hooks instead of async-listener.
|
4 |
|
5 | It need running nodejs version >= 8.2.1.
|
6 |
|
7 | ## Example
|
8 |
|
9 | ``` js
|
10 | const Session = require('./index')
|
11 |
|
12 | const session = new Session()
|
13 |
|
14 | function timeout (id) {
|
15 | session.scope(() => {
|
16 | session.set('a', id)
|
17 | setTimeout(() => {
|
18 | const a = session.get('a')
|
19 | console.log(a)
|
20 | })
|
21 | })
|
22 | }
|
23 |
|
24 | timeout(1)
|
25 | timeout(2)
|
26 | timeout(3)
|
27 |
|
28 | // Output:
|
29 | // 1
|
30 | // 2
|
31 | // 3
|
32 | ```
|
33 |
|
34 | ## session middleware in koa
|
35 |
|
36 | ``` js
|
37 | const app = new Koa()
|
38 | const session = new Session()
|
39 |
|
40 | const hello = 'hello, world'
|
41 |
|
42 | app.use(async (ctx, next) => {
|
43 | ctx.body = hello
|
44 | await next()
|
45 | })
|
46 |
|
47 | app.use(async (ctx, next) => {
|
48 | await session.scope(async () => {
|
49 | session.set('userId', 10086)
|
50 | await next()
|
51 | })
|
52 | })
|
53 |
|
54 | app.use((ctx) => {
|
55 | const userId = session.get('userId')
|
56 | console.log(userId)
|
57 | })
|
58 |
|
59 | app.listen(10086)
|
60 | ```
|
61 |
|
62 | ## Class: Session
|
63 |
|
64 | ### session.scope(callback)
|
65 |
|
66 | ### session.set(key, value)
|
67 |
|
68 | ### session.get(key)
|
69 |
|
70 | ### session.context
|
71 |
|