UNPKG

1.11 kBMarkdownView Raw
1# A cls session implementation using async_hooks
2
3Continuation Local Storage works like thread-local storage in threaded programming. This is a implementation of CLS using async_hooks instead of async-listener.
4
5It need running nodejs version >= 8.2.1.
6
7## Example
8
9``` js
10const Session = require('./index')
11
12const session = new Session()
13
14function 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
24timeout(1)
25timeout(2)
26timeout(3)
27
28// Output:
29// 1
30// 2
31// 3
32```
33
34## session middleware in koa
35
36``` js
37const app = new Koa()
38const session = new Session()
39
40const hello = 'hello, world'
41
42app.use(async (ctx, next) => {
43 ctx.body = hello
44 await next()
45})
46
47app.use(async (ctx, next) => {
48 await session.scope(async () => {
49 session.set('userId', 10086)
50 await next()
51 })
52})
53
54app.use((ctx) => {
55 const userId = session.get('userId')
56 console.log(userId)
57})
58
59app.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