Skip to content

Commit

Permalink
feat: beforeFn returns Promise<{header:{a:'b'}}> for axios's headers (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
BuptStEve authored Sep 25, 2019
1 parent 36addf5 commit e5ea0ef
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 7 deletions.
14 changes: 13 additions & 1 deletion docs/config/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,19 @@ export default {
详情参阅:[中间件进阶](../guide/middleware.md)

## beforeFn 发起请求前钩子函数
在请求发起前执行的函数(例如小程序可以通过返回 `header` 传递 `cookie`),因为是通过 `beforeFn().then(...)` 调用,所以注意要返回 Promise。
在请求发起前执行的函数,因为是通过 `beforeFn().then(...)` 调用,所以注意要返回 Promise。

例如小程序端可以通过返回 `header` 传递 `cookie`,web 端使用 axios 时也可以用来修改 `header`

> 虽然 axios 配置是 `headers` 但为了和小程序端保持一致就都用 `header`
```js
export default {
beforeFn: () => Promise.resolve({
header: { cookie: '1' },
}),
}
```

## afterFn 收到响应后的钩子函数
在收到响应后执行的函数,可以不用返回 `Promise`
Expand Down
15 changes: 15 additions & 0 deletions examples/apis-web/fake-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,20 @@ export default {
reqType: ('axios'),
mock: ({ mockCode }) => ({ code: mockCode, data: {} }),
},
/**
* beforeFnCookie
*/
{
name: 'beforeFnCookie',
path: 'beforeFn-cookie',
/**
* @returns {Promise<any>}
*/
beforeFn: () => Promise.resolve({
header: { cookie: '123' },
}),
/** @type { import('../../src/').ReqType } */
reqType: ('axios'),
},
],
}
3 changes: 2 additions & 1 deletion examples/apis-web/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const fakeGetApi: {
'afterData': ReqFnWithAnyParams
'mockFnData': ReqFnWithAnyParams
'noAfterData': ReqFnWithAnyParams
'beforeFnCookie': ReqFnWithAnyParams
'mockObjectData': ReqFnWithAnyParams
'empty-array-params': ReqFnWithAnyParams
'ap': ReqFn & {
Expand Down Expand Up @@ -53,4 +54,4 @@ export const fakePostApi: {
options?: RuntimeOptions
): Promise<T>
}
}
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tua-api",
"version": "1.3.5",
"version": "1.4.0",
"description": "🏗 A common tool helps converting configs to api functions",
"main": "dist/TuaApi.cjs.js",
"module": "dist/TuaApi.esm.js",
Expand Down Expand Up @@ -67,7 +67,7 @@
"koa-compose": "^4.1.0"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/core": "^7.6.2",
"@babel/plugin-external-helpers": "^7.2.0",
"@babel/plugin-proposal-decorators": "^7.6.0",
"@babel/plugin-proposal-object-rest-spread": "^7.5.5",
Expand Down
2 changes: 2 additions & 0 deletions src/adapters/wx.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export const getWxPromise = ({
complete: () => {
// 同步隐藏 loading
isShowLoading && hideLoadingFn()
/* istanbul ignore next */
rest.complete && rest.complete()
},
})
}
9 changes: 6 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ class TuaApi {
* @param {string} options.fullUrl 完整接口地址
* @param {string} options.reqType 使用什么工具发(axios/jsonp/wx)
* @param {object} options.reqParams 请求参数
* @param {object} options.header 请求的 header
* @param {string} options.callbackName 使用 jsonp 时的回调函数名
* @param {object} options.axiosOptions 透传 axios 配置参数
* @param {object} options.jsonpOptions 透传 fetch-jsonp 配置参数
Expand All @@ -107,6 +108,7 @@ class TuaApi {
_reqFn ({
url,
mock,
header,
method,
fullUrl,
reqType,
Expand All @@ -131,15 +133,16 @@ class TuaApi {
method = method.toLowerCase()

if (reqType === 'wx') {
return getWxPromise({ url, fullUrl, data, method, ...rest })
return getWxPromise({ url, fullUrl, data, method, header, ...rest })
}

if (reqType === 'axios') {
const params = {
...axiosOptions,
url: method === 'get' ? fullUrl : url,
data: method === 'get' ? {} : data,
method,
...axiosOptions,
headers: header,
}

return getAxiosPromise(params)
Expand Down Expand Up @@ -282,7 +285,7 @@ class TuaApi {

// 执行完 beforeFn 后执行的函数
const beforeFnCb = (rArgs = {}) => {
// 兼容小程序传递请求头(建议还是放在中间件中)
// 传递请求头
if (rArgs.header) {
ctx.req.reqFnParams.header = rArgs.header
}
Expand Down
15 changes: 15 additions & 0 deletions test/__tests__/axios.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const reqOHUrl = 'http://example-test.com/fake-post/own-host'
const reqTAUrl = 'http://example-base.com/fake-get/req-type-axios?asyncCp=asyncCp'
const reqEAPUrl = 'http://example-base.com/fake-post/empty-array-params'
const reqMFDUrl = 'http://example-base.com/fake-get/mock-function-data'
const reqBFCUrl = 'http://example-base.com/fake-get/beforeFn-cookie'

describe('middleware', () => {
test('change host before request', async () => {
Expand All @@ -30,6 +31,20 @@ describe('middleware', () => {
})
})

describe('beforeFn cookie', () => {
beforeEach(() => {
// @ts-ignore
mock.resetHistory()
})

test('set cookie by beforeFn', async () => {
mock.onGet(reqBFCUrl).reply(200, {})
await fakeGetApi.beforeFnCookie()

expect(mock.history.get[0].headers.cookie).toBe('123')
})
})

describe('mock data', () => {
test('mock function data', async () => {
mock.onGet(reqMFDUrl).reply(200, {})
Expand Down

0 comments on commit e5ea0ef

Please sign in to comment.