Skip to content

Commit

Permalink
feat: support function in params and commonParms
Browse files Browse the repository at this point in the history
  • Loading branch information
BuptStEve committed Apr 29, 2021
1 parent 20bc1f4 commit b92a06a
Show file tree
Hide file tree
Showing 13 changed files with 122 additions and 21 deletions.
10 changes: 10 additions & 0 deletions docs/config/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ export default {
}
```

::: tip
<badge text="1.7.0+" /> 后,支持函数模式

```js
export default {
commonParams: (params) => ({ t: Date.now(), foo: params.foo }),
}
```
:::

## axiosOptions 透传参数配置
由于 tua-api 是依赖于 `axios` 或是 `fetch-jsop` 来发送请求的。所以势必要提供参数透传的功能。

Expand Down
18 changes: 18 additions & 0 deletions docs/config/self.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,24 @@ export default {
}
```

::: tip
<badge text="1.7.0+" /> 后,支持函数模式

```js
export default {
pathList: [
{
...
params: (params) => ({
t: Date.now(),
foo: params.foo,
}),
},
],
}
```
:::

## commonParams 覆盖公共参数
有时某个接口正好不需要上一级中 `commonParams` 的参数。那么可以传递 `null` 覆盖上一级中的 `commonParams`

Expand Down
32 changes: 32 additions & 0 deletions examples/apis-web/fake-fn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export default {
// 该参数表示请求的公用服务器地址。
baseUrl: 'http://example-base.com/',

// 请求的中间路径,建议与文件同名,以便后期维护。
prefix: 'fake-fn',

// 所有请求都需要携带的参数
commonParams: (args) => ({
...args,
c: Math.random(),
}),

reqType: 'axios',

// 接口地址数组
pathList: [
/**
* fn-params
*/
{
name: 'fp',
path: 'fn-params',
method: 'post',
params: ({ param1, param2 }) => ({
t: Math.random(),
p1: param1,
p2: param2,
}),
},
],
}
10 changes: 2 additions & 8 deletions examples/apis-web/fake-post.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ export default {
/**
* empty-array-params
*/
{
name: 'eap',
path: 'empty-array-params',
},
{ name: 'eap', path: 'empty-array-params' },
/**
* array-params
*/
Expand Down Expand Up @@ -84,10 +81,7 @@ export default {
/**
* application/json
*/
{
name: 'pj',
path: 'post-json',
},
{ name: 'pj', path: 'post-json' },
/**
* raw-data
*/
Expand Down
9 changes: 9 additions & 0 deletions examples/apis-web/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,12 @@ export const fakePostApi: {
): Promise<T>
}
}

export const fakeFnApi: {
'fp': ReqFn & {
<T = Result>(
params: { t?: any },
options?: RuntimeOptions
): Promise<T>
}
}
1 change: 1 addition & 0 deletions examples/apis-web/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ tuaApi.use(async (ctx, next) => {
// console.log('after: ', ctx)
})

export const fakeFnApi = tuaApi.getApi(require('./fake-fn').default)
export const fakeGetApi = tuaApi.getApi(require('./fake-get').default)
export const fakePostApi = tuaApi.getApi(require('./fake-post').default)
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": "1.6.1",
"version": "1.7.0",
"description": "🏗 A common tool helps converting configs to api functions",
"main": "dist/TuaApi.cjs.js",
"module": "dist/TuaApi.esm.js",
Expand Down
4 changes: 2 additions & 2 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type Mock = AnyFunction | any

export type ApiConfig = WxApiConfig | WebApiConfig

export type ParamsConfig = string[] | ParamsObject
export type ParamsConfig = string[] | ParamsObject | ((args?: object) => object)

export type Middleware<T> = (ctx: T, next: () => Promise<any>) => Promise<any>

Expand Down Expand Up @@ -96,7 +96,7 @@ export interface BaseApiConfig {
beforeFn?: <T = any>() => Promise<T>
middleware?: Middleware<Ctx>[]
customFetch?: AnyPromiseFunction
commonParams?: object
commonParams?: object | ((args?: object) => object),
axiosOptions?: AxiosOptions
jsonpOptions?: JsonpOptions
useGlobalMiddleware?: boolean
Expand Down
11 changes: 6 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
map,
pipe,
isWx,
runFn,
logger,
mergeAll,
apiConfigToReqFnParams,
Expand Down Expand Up @@ -145,9 +146,7 @@ class TuaApi {

// mock data
if (mock) {
const resData = typeof mock === 'function'
? mock(data)
: { ...mock }
const resData = { ...runFn(mock, data) }

return Promise.resolve({ data: resData })
}
Expand Down Expand Up @@ -255,7 +254,7 @@ class TuaApi {
mock,
name,
path,
params = {},
params: rawParams = {},
prefix,
afterFn = ([x]) => x,
beforeFn = Promise.resolve.bind(Promise),
Expand Down Expand Up @@ -308,6 +307,8 @@ class TuaApi {
const apiFn = (args, runtimeOptions = {}) => {
args = args || {}

const params = runFn(rawParams, args)

// 最终的运行时配置,runtimeOptions 有最高优先级
const runtimeParams = {
type,
Expand Down Expand Up @@ -361,7 +362,7 @@ class TuaApi {

apiFn.key = `${prefix}/${apiName}`
apiFn.mock = mock
apiFn.params = params
apiFn.params = rawParams

return { [apiName]: apiFn }
}
Expand Down
6 changes: 4 additions & 2 deletions src/middlewareFns.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ERROR_STRINGS } from './constants'
import {
runFn,
isFormData,
combineUrls,
checkArrayParams,
Expand Down Expand Up @@ -59,7 +60,7 @@ const formatReqParamsMiddleware = (ctx, next) => {
const {
args,
params,
commonParams,
commonParams: rawCommonParams,
} = ctx.req

if (typeof args !== 'object') {
Expand All @@ -74,10 +75,11 @@ const formatReqParamsMiddleware = (ctx, next) => {

checkArrayParams(ctx.req)

const commonParams = runFn(rawCommonParams, args)
// 根据配置生成请求的参数
ctx.req.reqParams = Array.isArray(params)
? { ...commonParams, ...args }
: { ...getDefaultParamObj(ctx.req), ...args }
: { ...getDefaultParamObj({ ...ctx.req, commonParams }), ...args }

return next()
}
Expand Down
6 changes: 6 additions & 0 deletions src/utils/judge.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@ export const isFormData = (val) => (
(val instanceof FormData)
)

export const runFn = (fn, ...params) => {
if (typeof fn === 'function') return fn(...params)

return fn
}

export const isUndefined = val => typeof val === 'undefined'
3 changes: 0 additions & 3 deletions test/__tests__/axios.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ describe('fake post requests', () => {
})

test('form-data', async () => {
mock.resetHistory()
mock.onPost(reqOHUrl).reply(200, {})
const formData = new FormData()
formData.append('a', 'a')
Expand All @@ -169,7 +168,6 @@ describe('fake post requests', () => {
})

test('custom-transformRequest', async () => {
mock.resetHistory()
mock.onPost(reqCTUrl).reply(200, {})

await fakePostApi.ct()
Expand All @@ -180,7 +178,6 @@ describe('fake post requests', () => {
})

test('post-json', async () => {
mock.resetHistory()
mock.onPost(reqPjUrl).reply(200, {})

await fakePostApi.pj()
Expand Down
31 changes: 31 additions & 0 deletions test/__tests__/fn.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

import fakeFnConfig from '@examples/apis-web/fake-fn'
import { fakeFnApi } from '@examples/apis-web/'

const mock = new MockAdapter(axios)

const params = { param1: 'steve', param2: 'young' }
const reqFPUrl = 'http://example-base.com/fake-fn/fn-params'

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

test('should support function type params', async () => {
Math.random = jest.fn(() => 'foo')
mock.onPost(reqFPUrl).reply(200, {})
await fakeFnApi.fp(params)

const { data } = mock.history.post[0]
expect(data).toEqual(JSON.stringify({
...fakeFnConfig.commonParams(params),
t: 'foo',
p1: params.param1,
p2: params.param2,
}))
});
});

0 comments on commit b92a06a

Please sign in to comment.