Skip to content

Commit

Permalink
feat(axios): close #32, support FormData type params (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
BuptStEve authored Apr 23, 2019
1 parent 17825c7 commit a669662
Show file tree
Hide file tree
Showing 13 changed files with 82 additions and 11 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ module.exports = {
},
globals: {
wx: true,
FormData: true,
},
}
1 change: 1 addition & 0 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ module.exports = {
'middleware',
'mock',
'export-utils',
'form-data',
'../config/',
],
},
Expand Down
2 changes: 1 addition & 1 deletion docs/config/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export default {
```

## reqType 请求使用库类型
即用哪个库发起请求目前支持:jsonp、axios,不填则使用默认配置
即用哪个库发起请求目前支持:jsonp、axios、wx,不填则使用默认配置中的 reqType

```js
export default {
Expand Down
2 changes: 1 addition & 1 deletion docs/config/default.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ new TuaApi({
例如 `https://example.com/api/`

## reqType 请求类型
即在 web 端使用哪个库发起请求目前支持:jsonp、axios,不填默认使用 axios。(小程序端没得选...)
即使用哪个库发起请求目前支持:jsonp、axios、wx,不填默认使用 axios。

## middleware 中间件函数数组
【所有】请求都会调用的中间件函数数组!适合添加一些通用逻辑,例如接口上报。
Expand Down
28 changes: 28 additions & 0 deletions docs/guide/form-data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# FormData <Badge text="1.3.0+"/>
## 发送二进制数据
日常使用中,除了简单的字符串参数以外,有时也会遇到需要发送二进制数据的场景,例如上传文件。

在旧版的 `tua-api` 中若是遇到这种请求,也能发送但比较繁琐。

```js
const formData = new FormData()

imgUploadApi.userUpload(null, {
reqFnParams: { reqParams: formData },
axiosOptions: { transformRequest: null },
})
```

如上例所示,借助第二个参数[运行时配置](../config/runtime.md)设置了:数据、 `transformRequest`

而在新版本的 `tua-api` 中,只要这么调用即可:

```js
const formData = new FormData()

imgUploadApi.userUpload(formData)
```

实现原理是 `tua-api` 在底层判断出接收的接口参数是 `FormData` 类型的数据,自动设置了 `transformRequest`

> 小程序端暂时建议使用原生的 `wx.uploadFile`
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tua-api",
"version": "1.2.1",
"version": "1.3.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 @@ -58,6 +58,7 @@
},
"eslintIgnore": [
"dist/*",
"!.eslintrc.js",
"package.json"
],
"dependencies": {
Expand Down
8 changes: 6 additions & 2 deletions src/adapters/axios.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios'

import { DEFAULT_HEADER } from '../constants'
import { logger, getParamStrFromObj } from '../utils'
import { logger, isFormData, getParamStrFromObj } from '../utils'

// 获取使用 axios 发起请求后的 promise 对象
export const getAxiosPromise = ({
Expand All @@ -14,11 +14,15 @@ export const getAxiosPromise = ({
transformRequest = [getParamStrFromObj],
...rest
}) => {
const isFD = isFormData(data)

logger.log(`Req Url: ${url}`)
if (data && Object.keys(data).length) {
if (data && (Object.keys(data).length || isFD)) {
logger.log(`Req Data:`, data)
}

transformRequest = isFD ? null : transformRequest

return axios({
url,
data,
Expand Down
7 changes: 7 additions & 0 deletions src/middlewareFns.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ERROR_STRINGS } from './constants'
import {
isFormData,
checkArrayParams,
getParamStrFromObj,
getDefaultParamObj,
Expand Down Expand Up @@ -64,6 +65,12 @@ const formatReqParamsMiddleware = (ctx, next) => {
throw TypeError(ERROR_STRINGS.argsType)
}

if (isFormData(args)) {
ctx.req.reqParams = args

return next()
}

checkArrayParams(ctx.req)

// 根据配置生成请求的参数
Expand Down
4 changes: 0 additions & 4 deletions src/utils/env.js

This file was deleted.

2 changes: 1 addition & 1 deletion src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export * from './fp'
export * from './mp'
export * from './env'
export * from './judge'
export * from './logger'
export * from './params'
9 changes: 9 additions & 0 deletions src/utils/judge.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const isWx = () => (
typeof wx !== 'undefined' &&
typeof wx.request === 'function'
)

export const isFormData = (val) => (
(typeof FormData !== 'undefined') &&
(val instanceof FormData)
)
5 changes: 4 additions & 1 deletion test/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
module.exports = {
env: { jest: true }
env: { jest: true },
globals: {
FormData: true,
},
}
21 changes: 21 additions & 0 deletions test/__tests__/axios.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ describe('fake get requests', () => {
})

describe('fake post requests', () => {
beforeEach(() => {
mock.resetHistory()
})

test('own-host', async () => {
const data = { code: 0, data: 'own-host' }
mock.onPost(reqOHUrl).reply(200, data)
Expand Down Expand Up @@ -123,4 +127,21 @@ describe('fake post requests', () => {

expect(resData).toEqual({ code: 0, data: 'array data' })
})

test('form-data', async () => {
mock.onPost(reqOHUrl).reply(200, {})
const formData = new FormData()
formData.append('a', 'a')
formData.append('b', 123)

await fakePostApi.oh(formData)

const {
data,
transformRequest,
} = mock.history.post[0]

expect(data).toBe(formData)
expect(transformRequest[0].name).toBe('transformRequest')
})
})

0 comments on commit a669662

Please sign in to comment.