Skip to content

Commit df00656

Browse files
author
jun.zhua
committed
✨✅add koa middleware and test case
1 parent 61be6a7 commit df00656

File tree

8 files changed

+206
-131
lines changed

8 files changed

+206
-131
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,6 @@ bower_components/
4444
.tern-project
4545
cscope.*
4646

47+
# nyc coverage
48+
.nyc_output/
4749

README.md

+49-4
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
11
# HTTP Request Context
22

3+
[![npm package](https://nodei.co/npm/http-request-context.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
4+
5+
[![npm package](https://img.shields.io/npm/v/http-request-context.svg?style=flat-square)](https://www.npmjs.org/package/http-request-context)
6+
[![NPM downloads](https://img.shields.io/npm/dm/http-request-context.svg?style=flat-square)](https://npmjs.org/package/http-request-context)
7+
[![Dependency Status](https://david-dm.org/zhujun24/http-request-context.svg?style=flat-square)](https://david-dm.org/zhujun24/http-request-context)
8+
39
Get and set request-scoped context anywhere.
410

511
## How to Use
612

713
Install: `npm install http-request-context --save`
814

9-
### Init in middleware
15+
### Express
16+
17+
#### Init
1018

1119
```js
12-
const express = require('express')
1320
const httpRequestContext = require('http-request-context')
1421

15-
const app = express()
16-
1722
app.use(httpRequestContext.middleware)
1823
```
1924

@@ -39,6 +44,41 @@ const httpRequestContext = require('http-request-context')
3944
httpRequestContext.get('foo') // 'bar'
4045
```
4146

47+
### Koa
48+
49+
#### Init
50+
51+
```js
52+
const httpRequestContext = require('http-request-context')
53+
54+
app.use(httpRequestContext.koaMiddleware)
55+
```
56+
57+
### Set Context
58+
59+
```js
60+
const httpRequestContext = require('http-request-context')
61+
62+
// set context by key-value
63+
app.use(async (ctx, next) => {
64+
await new Promise(resolve => {
65+
setTimeout(() => {
66+
httpRequestContext.set('user', 'user')
67+
resolve()
68+
}, 300)
69+
})
70+
await next()
71+
})
72+
```
73+
74+
### Get Context
75+
76+
```js
77+
const httpRequestContext = require('http-request-context')
78+
79+
httpRequestContext.get('foo') // 'bar'
80+
```
81+
4282
## Tips
4383

4484
### MySQL
@@ -60,3 +100,8 @@ util.promisify(mysqlConnection.query).bind(mysqlConnection)('SELECT * FROM table
60100
})
61101
.catch(error => {})
62102
```
103+
104+
## TODO
105+
106+
- [ ] Get undefined in koa close callback
107+
- [ ] Get undefined in borderline case

example/express.js

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,41 @@
11
const util = require('util')
2-
const request = require('request')
32
const express = require('express')
43
const asyncHooks = require('async_hooks')
54
const httpRequestContext = require('../')
65

7-
var app = express();
6+
var app = express()
87

9-
app.use(httpRequestContext.middleware);
8+
app.use(httpRequestContext.middleware)
109

1110
app.use((req, res, next) => {
12-
const start = Date.now()
1311
res.on('close', () => {
1412
console.log('close', httpRequestContext.get('user'))
1513
})
1614
res.once('finish', () => {
17-
console.log('finish', asyncHooks.executionAsyncId(), httpRequestContext.get('user'), req.query)
15+
console.log('finish', asyncHooks.executionAsyncId(), httpRequestContext.get('user'))
1816
})
1917
next()
2018
})
2119

2220
app.use((req, res, next) => {
23-
httpRequestContext.set('user', 'user')
24-
next();
25-
});
21+
setTimeout(() => {
22+
httpRequestContext.set('user', 'user')
23+
next()
24+
}, 300)
25+
})
2626

2727
app.use((req, res, next) => {
2828
util.promisify(process.nextTick)().then(() => {
2929
httpRequestContext.set('age', '99')
30-
next();
30+
next()
3131
})
32-
});
32+
})
3333

3434
app.all('*', (req, res) => {
35-
request('https://www.baidu.com/', () => {
36-
res.send(httpRequestContext.get('user'))
35+
res.send({
36+
user: httpRequestContext.get('user'),
37+
age: httpRequestContext.get('age')
3738
})
3839
})
3940

40-
app.listen(3001);
41+
app.listen(3001)

example/koa.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const util = require('util')
2+
const Koa = require('koa')
3+
const asyncHooks = require('async_hooks')
4+
const httpRequestContext = require('../')
5+
6+
const app = new Koa()
7+
8+
app.use(httpRequestContext.koaMiddleware)
9+
10+
app.use(async (ctx, next) => {
11+
ctx.req.on('close', () => {
12+
console.log('close', httpRequestContext.get('user'))
13+
})
14+
ctx.res.on('finish', () => {
15+
console.log('finish', asyncHooks.executionAsyncId(), httpRequestContext.get('user'))
16+
})
17+
await next()
18+
})
19+
20+
app.use(async (ctx, next) => {
21+
await new Promise(resolve => {
22+
setTimeout(() => {
23+
httpRequestContext.set('user', 'user')
24+
resolve()
25+
}, 300)
26+
})
27+
await next()
28+
})
29+
30+
app.use(async (ctx, next) => {
31+
await util.promisify(process.nextTick)().then(() => {
32+
httpRequestContext.set('age', '99')
33+
})
34+
await next()
35+
})
36+
37+
app.use(ctx => {
38+
ctx.body = {
39+
user: httpRequestContext.get('user'),
40+
age: httpRequestContext.get('age')
41+
}
42+
})
43+
44+
app.listen(3002)

index.js

+8-11
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ const asyncHooks = require('async_hooks')
22

33
const contexts = {}
44
const rootAsyncIdQueueMap = {}
5-
const INTERVAL = 1000
6-
const ID_TIMEOUT = 60000
5+
const INTERVAL = 10000
6+
const ID_TIMEOUT = 150000
77

88
// delete asyncId map 60s ago every second
99
const interval = () => {
@@ -30,15 +30,6 @@ const findRootId = (id) => {
3030
}
3131
}
3232

33-
const removeAsyncId = id => {
34-
Object.keys(contexts).forEach(cacheId => {
35-
if (contexts[cacheId].id === id) {
36-
delete contexts[cacheId]
37-
removeAsyncId(cacheId)
38-
}
39-
})
40-
}
41-
4233
asyncHooks.createHook({
4334
init (asyncId, type, triggerAsyncId) {
4435
contexts[asyncId] = {
@@ -77,6 +68,12 @@ module.exports = {
7768
rootAsyncIdQueueMap[executionAsyncId] = []
7869
next()
7970
},
71+
koaMiddleware: async (ctx, next) => {
72+
const executionAsyncId = asyncHooks.executionAsyncId()
73+
contexts[executionAsyncId].data = {}
74+
rootAsyncIdQueueMap[executionAsyncId] = []
75+
await next()
76+
},
8077
set: (key, value) => {
8178
const rootId = findRootId(asyncHooks.executionAsyncId())
8279
if (rootId) {

namespace.js

-100
This file was deleted.

package.json

+19-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
{
22
"name": "http-request-context",
3-
"version": "0.0.3",
3+
"version": "0.0.4",
44
"description": "Store context in http middleware lifecycle.",
55
"main": "index.js",
66
"scripts": {
7-
"test": "echo \"Error: no test specified\" && exit 1"
7+
"fix": "standard \"**/**.js\" --fix",
8+
"lint": "standard \"**/**.js\"",
9+
"test": "mocha --exit",
10+
"coverage": "nyc --reporter=text --reporter=lcov npm test"
811
},
912
"repository": {
1013
"type": "git",
1114
"url": "git+https://github.com/zhujun24/http-request-context.git"
1215
},
16+
"pre-commit": [
17+
"lint",
18+
"test",
19+
"coverage"
20+
],
1321
"keywords": [
1422
"http",
1523
"request",
@@ -22,7 +30,15 @@
2230
},
2331
"homepage": "https://github.com/zhujun24/http-request-context#readme",
2432
"devDependencies": {
33+
"assert": "^2.0.0",
34+
"chai": "^4.2.0",
35+
"chai-http": "^4.3.0",
2536
"express": "^4.17.1",
26-
"request": "^2.88.0"
37+
"koa": "^2.8.1",
38+
"mocha": "^6.2.0",
39+
"nyc": "^14.1.1",
40+
"pre-commit": "^1.2.2",
41+
"request": "^2.88.0",
42+
"standard": "^14.1.0"
2743
}
2844
}

0 commit comments

Comments
 (0)