Skip to content

Commit

Permalink
fix: ctx.reqTime is undefined in middleware (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
BuptStEve authored Oct 31, 2018
1 parent fdd3f79 commit 22e9adc
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tua-api",
"version": "0.2.1",
"version": "0.2.2",
"main": "dist/umd.js",
"module": "dist/es.js",
"jsnext:main": "dist/es.js",
Expand Down
7 changes: 5 additions & 2 deletions src/TuaApiCore.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
formatResDataMiddleware,
recordReqTimeMiddleware,
updateFullUrlMiddleware,
recordStartTimeMiddleware,
formatReqParamsMiddleware,
} from './middlewareFns'

Expand Down Expand Up @@ -101,12 +102,14 @@ class TuaApiCore {
: middleware

return koaCompose([
// 记录时间
recordReqTimeMiddleware,
// 记录开始时间
recordStartTimeMiddleware,
// 格式化生成请求参数
formatReqParamsMiddleware,
// 业务侧中间件函数数组
...middlewareFns,
// 记录结束时间
recordReqTimeMiddleware,
// 更新请求参数
updateFullUrlMiddleware,
// 统一转换响应数据为对象
Expand Down
14 changes: 12 additions & 2 deletions src/middlewareFns.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@ import {
} from './utils'

/**
* 记录请求开始时间、接受响应时间和请求总时间的中间件
* 记录请求开始时间
* @param {Object} ctx 上下文对象
* @param {Function} next 转移控制权给下一个中间件的函数
*/
const recordReqTimeMiddleware = (ctx, next) => {
const recordStartTimeMiddleware = (ctx, next) => {
ctx.startTime = Date.now()

return next()
}

/**
* 记录接受响应时间和请求总时间的中间件
* @param {Object} ctx 上下文对象
* @param {Function} next 转移控制权给下一个中间件的函数
*/
const recordReqTimeMiddleware = (ctx, next) => {
return next().then(() => {
ctx.endTime = Date.now()
ctx.reqTime = Date.now() - ctx.startTime
Expand Down Expand Up @@ -98,5 +107,6 @@ export {
recordReqTimeMiddleware,
formatResDataMiddleware,
updateFullUrlMiddleware,
recordStartTimeMiddleware,
formatReqParamsMiddleware,
}
3 changes: 3 additions & 0 deletions test/__tests__/core.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ describe('middleware', () => {
const tuaApi = new TuaApiMp()
const globalMiddlewareFn = jest.fn(async (ctx, next) => {
await next()

expect(ctx.endTime).toBeDefined()
expect(ctx.reqTime).toBeDefined()
})
tuaApi.use(globalMiddlewareFn)

Expand Down

0 comments on commit 22e9adc

Please sign in to comment.