@lx-frontend/multi-ajax 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.babelrc.json +5 -0
- package/CHANGELOG.md +7 -0
- package/README.md +205 -0
- package/__tests__/lx-frontend-ajax.test.js +7 -0
- package/build/rollup.config.cjs.js +43 -0
- package/build/rollup.config.esm.js +40 -0
- package/build/scripts/patch-axios-post-install.js +45 -0
- package/build/scripts/patch-content.txt +67 -0
- package/lib/ajax.cjs.js +1 -0
- package/lib/ajax.esm.js +1 -0
- package/lib/types/adapters/index.d.ts +2 -0
- package/lib/types/adapters/wx-adapter.d.ts +2 -0
- package/lib/types/canceller.d.ts +2 -0
- package/lib/types/compatibleMethods.d.ts +6 -0
- package/lib/types/helpers.d.ts +11 -0
- package/lib/types/index.d.ts +2 -0
- package/lib/types/methods.d.ts +9 -0
- package/lib/types/types.d.ts +40 -0
- package/lib/types/utils.d.ts +10 -0
- package/package.json +44 -0
- package/src/adapters/index.ts +5 -0
- package/src/adapters/wx-adapter.ts +86 -0
- package/src/canceller.ts +5 -0
- package/src/compatibleMethods.ts +54 -0
- package/src/helpers.ts +45 -0
- package/src/index.ts +39 -0
- package/src/methods.ts +80 -0
- package/src/types.ts +47 -0
- package/src/utils.ts +62 -0
- package/tsconfig.json +15 -0
package/CHANGELOG.md
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
## @lx-frontend/ajax
|
|
2
|
+
|
|
3
|
+
一个规范Ajax使用的框架
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
使用npm:
|
|
8
|
+
|
|
9
|
+
`npm install @lx-frontend/ajax`
|
|
10
|
+
|
|
11
|
+
使用yarn:
|
|
12
|
+
|
|
13
|
+
`yarn add @lx-frontend/ajax`
|
|
14
|
+
|
|
15
|
+
## 特别说明
|
|
16
|
+
|
|
17
|
+
`@lx-frontend/ajax`是基于`axios`开发的,同时对微信小程序请求引擎做了适配,但是axios并不支持微信小程序环境,在小程序环境下会直接报错,所以`@lx-frontend/ajax`在安装完成后会对`axios`的文件做一些修改以适配微信环境,详见`package.json`的`postinstall`命令。
|
|
18
|
+
|
|
19
|
+
`@lx-frontend/ajax`并没有将`axios`的代码打包进目标代码,所以`postinstall`命令还需要在使用该库的项目中执行。所以,需要在项目根目录下,`.npmrc`文件中写入`side-effects-cache=false`配置,保证每次安装都能执行postinstall命令。
|
|
20
|
+
|
|
21
|
+
## 用法
|
|
22
|
+
|
|
23
|
+
### 创建ajax实例
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
// 创建ajax实例
|
|
27
|
+
import initAjax from '@lx-frontend/ajax'
|
|
28
|
+
|
|
29
|
+
const ajax = initAjax({
|
|
30
|
+
baseURL: 'api/v1',
|
|
31
|
+
mock: null
|
|
32
|
+
// ... 自定义配置项 或者 axios支持的配置
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// 创建一个get请求函数
|
|
36
|
+
const getRequest = ajax.get('/get/url', {/* 请求配置(自定义 or ajax支持的配置) */})
|
|
37
|
+
// 发送请求
|
|
38
|
+
getRequest({/* url参数,将以请求参数的形式挂载到url的末尾 */}, {/* 请求配置,拥有最高的优先级 */}).then(res => {})
|
|
39
|
+
|
|
40
|
+
// 创建一个post请求
|
|
41
|
+
const postRequest = ajax.post('/post/url', {/* 请求配置(自定义 or ajax支持的配置) */})
|
|
42
|
+
// 发送请求
|
|
43
|
+
postRequest({/* 请求需要发送的数据 */}, {/* 请求配置,拥有最高的优先级 */}).then(res => {})
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 取消请求
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
// 下面以一个get请求演示如何取消请求
|
|
50
|
+
|
|
51
|
+
const ajax = initAjax({/* ... */})
|
|
52
|
+
|
|
53
|
+
// 创建get请求时,配置项
|
|
54
|
+
const getRequest = ajax.get('/get/url')
|
|
55
|
+
// 发送请求时,配置项传递一个字符串给cancelKey,此时ajax实例上将挂载一个以该字符串命名的函数,此函数就是该请求的取消函数
|
|
56
|
+
getRequest({/* url参数,将以请求参数的形式挂载到url的末尾 */}, { cancelKey: 'cancelGetRequest' }).then(res => {})
|
|
57
|
+
|
|
58
|
+
// 此处中断请求
|
|
59
|
+
ajax.canceller.cancelGetRequest()
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
## options配置
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
{
|
|
66
|
+
// boolean,是否发送FormData类型的数据,如果为true,则会将data数据转化成FormData形式,且修改请求头header中的Content-Type字段,默认为false,发送json数据
|
|
67
|
+
baseURL
|
|
68
|
+
// 发送FormData格式的数据,仅适用于post类请求
|
|
69
|
+
sendFormData
|
|
70
|
+
// 如果该参数不为空,请求将不会真正发出,而是直接resolve该数据
|
|
71
|
+
mock
|
|
72
|
+
// string,如果请求传递了该参数,则调用ajax.canceller[cancelKey]()将中断该请求
|
|
73
|
+
cancelKey
|
|
74
|
+
// ... 其他axios支持的所有配置
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## 拦截器(interceptor)
|
|
79
|
+
|
|
80
|
+
ajax拦截器同axios的拦截器使用方法完全一样,示例如下:
|
|
81
|
+
|
|
82
|
+
```js
|
|
83
|
+
const ajax = initAjax({/* ... */})
|
|
84
|
+
|
|
85
|
+
// 请求拦截器注册
|
|
86
|
+
ajax.interceptors.request.use(interceptRequest)
|
|
87
|
+
// 请求成功或失败拦截器
|
|
88
|
+
ajax.interceptors.response.use(interceptSuccess, interceptFail)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## TS支持
|
|
92
|
+
|
|
93
|
+
### 自定义配置的校验和提示功能
|
|
94
|
+
|
|
95
|
+
共有三个地方可以传递自定义配置
|
|
96
|
+
1. 实例化ajax时传递的参数
|
|
97
|
+
```js
|
|
98
|
+
const ajax = initAjax({/* options here */})
|
|
99
|
+
```
|
|
100
|
+
此处配置的参数作用于所有的ajax请求
|
|
101
|
+
|
|
102
|
+
2. 创建ajax请求函数时传递的参数
|
|
103
|
+
```js
|
|
104
|
+
const getRequest = ajax.get('get/url', {/* options here */})
|
|
105
|
+
```
|
|
106
|
+
此处的配置优先级高于全局
|
|
107
|
+
|
|
108
|
+
3. ajax请求函数调用时
|
|
109
|
+
```js
|
|
110
|
+
const getRequest = ajax.get('get/url', {/* options here */})
|
|
111
|
+
|
|
112
|
+
getRequest(params, {/* options here */})
|
|
113
|
+
```
|
|
114
|
+
此处的优先级最高
|
|
115
|
+
|
|
116
|
+
那么,在编码时,TS如何校验参数传递的是否正确,以及获得配置的提示功能呢?
|
|
117
|
+
|
|
118
|
+
实际上,ajax的初始化函数`initAjax`函数是一个泛型函数,可以接受两个类型作为参数,其中第一个类型参数便是对自定义参数的描述。
|
|
119
|
+
|
|
120
|
+
举例如下:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
// 假设我们有cusOpt1和cusOpt2两个自定义参数,类型分别为boolean和string
|
|
124
|
+
// 自定义参数的描述
|
|
125
|
+
interface CustomOpt {
|
|
126
|
+
cusOpt1: boolean;
|
|
127
|
+
cusOpt2: string
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 那么,在实例化ajax时
|
|
131
|
+
const ajax = initAjax<CustomOpt>({/* options here */})
|
|
132
|
+
|
|
133
|
+
// 此时,以上三个可以传递自定义参数的地方就拥有了自定义参数的校验和提示功能
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### 请求返回数据的类型
|
|
137
|
+
|
|
138
|
+
假设我们有如下请求
|
|
139
|
+
```ts
|
|
140
|
+
// 创建ajax实例
|
|
141
|
+
import initAjax from '@lx-frontend/ajax'
|
|
142
|
+
|
|
143
|
+
const ajax = initAjax({/* ... */})
|
|
144
|
+
|
|
145
|
+
// 创建一个get请求函数
|
|
146
|
+
const getRequest = ajax.get('/get/url')
|
|
147
|
+
// 发送请求
|
|
148
|
+
getRequest(params).then(res => {
|
|
149
|
+
// 如何获得res数据的代码提示功能
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`getRequest`调用发出请求,返回一个Promise,在then回调中获取到了请求的数据,希望在回调函数中能够知道res的结构,获得编码提示功能
|
|
154
|
+
|
|
155
|
+
同自定义参数的代码提示一样,需要我们自己传入对返回数据的描述
|
|
156
|
+
|
|
157
|
+
有两个地方可以传递该描述:
|
|
158
|
+
1. ajax的实例化函数,该函数的第二个泛型参数便是对返回数据的描述,该描述将作用于全局
|
|
159
|
+
2. ajax的实例方法,比如ajax.get,该实例方法可接受一个泛型参数用来描述返回数据的结构,该描述将覆盖全局参数
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// 自定义参数描述
|
|
163
|
+
interface CustomOpt {
|
|
164
|
+
cusOpt1: boolean;
|
|
165
|
+
cusOpt2: string
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
interface GResShape {
|
|
169
|
+
code: number;
|
|
170
|
+
message: string;
|
|
171
|
+
data: any
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 那么,在实例化ajax时
|
|
175
|
+
const ajax = initAjax<CustomOpt, GResShape>({/* options here */})
|
|
176
|
+
|
|
177
|
+
// 创建一个get请求函数
|
|
178
|
+
const getRequest = ajax.get('/get/url')
|
|
179
|
+
// 发送请求
|
|
180
|
+
getRequest(params).then(res => {
|
|
181
|
+
// 在这里,ts将res推导为GResShape结构
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
// 上面的方式使得全局的ajax请求都将返回的数据类型推导为GResShape,但是假设个别请求有特殊的返回格式,或者想进一步对上面data的类型进行描述,该怎么办?
|
|
186
|
+
// 利用ajax方法可以接收一个泛型参数的能力,获得个性化的返回类型推导能力:
|
|
187
|
+
|
|
188
|
+
interface LocResShape {
|
|
189
|
+
code: number;
|
|
190
|
+
message: string;
|
|
191
|
+
data: {
|
|
192
|
+
images: string[];
|
|
193
|
+
pages: number;
|
|
194
|
+
totalCount: number;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// 创建一个get请求函数
|
|
199
|
+
const getRequest = ajax.get<LocResShape>('/get/url')
|
|
200
|
+
// 发送请求
|
|
201
|
+
getRequest(params).then(res => {
|
|
202
|
+
// 在这里,ts将res推导为LocResShape结构
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
```
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import babel from '@rollup/plugin-babel'
|
|
2
|
+
import commonjs from '@rollup/plugin-commonjs'
|
|
3
|
+
import resolve from '@rollup/plugin-node-resolve'
|
|
4
|
+
import typescript from '@rollup/plugin-typescript'
|
|
5
|
+
import terser from '@rollup/plugin-terser'
|
|
6
|
+
import json from '@rollup/plugin-json'
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
input: 'src/index.ts',
|
|
10
|
+
output: {
|
|
11
|
+
file: 'lib/ajax.cjs.js',
|
|
12
|
+
exports: 'default',
|
|
13
|
+
format: 'cjs',
|
|
14
|
+
},
|
|
15
|
+
plugins: [
|
|
16
|
+
resolve({
|
|
17
|
+
preferBuiltins: true,
|
|
18
|
+
}),
|
|
19
|
+
commonjs(),
|
|
20
|
+
babel({
|
|
21
|
+
babelrc: false,
|
|
22
|
+
presets: [
|
|
23
|
+
[
|
|
24
|
+
'@babel/preset-env',
|
|
25
|
+
{
|
|
26
|
+
targets: {
|
|
27
|
+
node: '10.0',
|
|
28
|
+
browsers: 'last 1 version, > 1%',
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
],
|
|
32
|
+
],
|
|
33
|
+
plugins: [['@babel/plugin-transform-runtime', { useESModules: false }]],
|
|
34
|
+
babelHelpers: 'runtime',
|
|
35
|
+
}),
|
|
36
|
+
typescript({
|
|
37
|
+
noForceEmit: true,
|
|
38
|
+
}),
|
|
39
|
+
json(),
|
|
40
|
+
terser(),
|
|
41
|
+
],
|
|
42
|
+
external: [/@babel\/runtime/, 'axios', 'qs'],
|
|
43
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import babel from '@rollup/plugin-babel'
|
|
2
|
+
import commonjs from '@rollup/plugin-commonjs'
|
|
3
|
+
import resolve from '@rollup/plugin-node-resolve'
|
|
4
|
+
import typescript from '@rollup/plugin-typescript'
|
|
5
|
+
import terser from '@rollup/plugin-terser'
|
|
6
|
+
import json from '@rollup/plugin-json'
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
input: 'src/index.ts',
|
|
10
|
+
output: {
|
|
11
|
+
file: 'lib/ajax.esm.js',
|
|
12
|
+
format: 'es',
|
|
13
|
+
},
|
|
14
|
+
plugins: [
|
|
15
|
+
resolve({
|
|
16
|
+
preferBuiltins: true,
|
|
17
|
+
}),
|
|
18
|
+
commonjs(),
|
|
19
|
+
babel({
|
|
20
|
+
babelrc: false,
|
|
21
|
+
presets: [
|
|
22
|
+
[
|
|
23
|
+
'@babel/preset-env',
|
|
24
|
+
{
|
|
25
|
+
targets: {
|
|
26
|
+
node: '10.0',
|
|
27
|
+
browsers: 'last 1 version, > 1%',
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
],
|
|
32
|
+
plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]],
|
|
33
|
+
babelHelpers: 'runtime',
|
|
34
|
+
}),
|
|
35
|
+
typescript(),
|
|
36
|
+
json(),
|
|
37
|
+
terser(),
|
|
38
|
+
],
|
|
39
|
+
external: [/@babel\/runtime/, 'axios', 'qs'],
|
|
40
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
const resolve = require('resolve/sync');
|
|
4
|
+
|
|
5
|
+
function resolveAxiosPath() {
|
|
6
|
+
var res = resolve('axios', { basedir: __dirname });
|
|
7
|
+
return path.dirname(res)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function patchBrowserIndex(axiosPath) {
|
|
11
|
+
const patchPath = path.resolve(axiosPath, 'lib/platform/browser/index.js')
|
|
12
|
+
|
|
13
|
+
// TODO: 验证axios版本
|
|
14
|
+
// TODO:确定在pnpm下,如果存在多个axios版本会怎样?
|
|
15
|
+
|
|
16
|
+
const contentPath = path.resolve(__dirname, './patch-content.txt')
|
|
17
|
+
const patchContent = fs.readFileSync(contentPath)
|
|
18
|
+
|
|
19
|
+
console.log('patched axios file:', patchPath)
|
|
20
|
+
fs.writeFileSync(patchPath, patchContent)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function patchAxiosPackageJson(axiosPath) {
|
|
24
|
+
const packagePath = path.resolve(axiosPath, 'package.json')
|
|
25
|
+
|
|
26
|
+
const contentObj = require(packagePath)
|
|
27
|
+
|
|
28
|
+
const exportDot = contentObj.exports['.']
|
|
29
|
+
|
|
30
|
+
exportDot.browser.require = './index.js'
|
|
31
|
+
exportDot.default.require = './index.js'
|
|
32
|
+
|
|
33
|
+
fs.writeFileSync(packagePath, JSON.stringify(contentObj), {encoding: 'utf8'})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function patchAxios() {
|
|
37
|
+
|
|
38
|
+
const axiosPath = resolveAxiosPath()
|
|
39
|
+
|
|
40
|
+
patchBrowserIndex(axiosPath)
|
|
41
|
+
|
|
42
|
+
patchAxiosPackageJson(axiosPath)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
patchAxios()
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import URLSearchParams from './classes/URLSearchParams.js'
|
|
2
|
+
import FormData from './classes/FormData.js'
|
|
3
|
+
import Blob from './classes/Blob.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Determine if we're running in a standard browser environment
|
|
7
|
+
*
|
|
8
|
+
* This allows axios to run in a web worker, and react-native.
|
|
9
|
+
* Both environments support XMLHttpRequest, but not fully standard globals.
|
|
10
|
+
*
|
|
11
|
+
* web workers:
|
|
12
|
+
* typeof window -> undefined
|
|
13
|
+
* typeof document -> undefined
|
|
14
|
+
*
|
|
15
|
+
* react-native:
|
|
16
|
+
* navigator.product -> 'ReactNative'
|
|
17
|
+
* nativescript
|
|
18
|
+
* navigator.product -> 'NativeScript' or 'NS'
|
|
19
|
+
*
|
|
20
|
+
* @returns {boolean}
|
|
21
|
+
*/
|
|
22
|
+
const isStandardBrowserEnv = (() => {
|
|
23
|
+
// 针对微信小程序环境打补丁
|
|
24
|
+
if (typeof wx !== 'undefined' && typeof wx.request === 'function') return false
|
|
25
|
+
|
|
26
|
+
let product;
|
|
27
|
+
if (typeof navigator !== 'undefined' && (
|
|
28
|
+
(product = navigator.product) === 'ReactNative' ||
|
|
29
|
+
product === 'NativeScript' ||
|
|
30
|
+
product === 'NS')
|
|
31
|
+
) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
36
|
+
})();
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Determine if we're running in a standard browser webWorker environment
|
|
40
|
+
*
|
|
41
|
+
* Although the `isStandardBrowserEnv` method indicates that
|
|
42
|
+
* `allows axios to run in a web worker`, the WebWorker will still be
|
|
43
|
+
* filtered out due to its judgment standard
|
|
44
|
+
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
|
|
45
|
+
* This leads to a problem when axios post `FormData` in webWorker
|
|
46
|
+
*/
|
|
47
|
+
const isStandardBrowserWebWorkerEnv = (() => {
|
|
48
|
+
return (
|
|
49
|
+
typeof WorkerGlobalScope !== 'undefined' &&
|
|
50
|
+
// eslint-disable-next-line no-undef
|
|
51
|
+
self instanceof WorkerGlobalScope &&
|
|
52
|
+
typeof self.importScripts === 'function'
|
|
53
|
+
);
|
|
54
|
+
})();
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
export default {
|
|
58
|
+
isBrowser: true,
|
|
59
|
+
classes: {
|
|
60
|
+
URLSearchParams,
|
|
61
|
+
FormData,
|
|
62
|
+
Blob
|
|
63
|
+
},
|
|
64
|
+
isStandardBrowserEnv,
|
|
65
|
+
isStandardBrowserWebWorkerEnv,
|
|
66
|
+
protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
|
|
67
|
+
};
|
package/lib/ajax.cjs.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("axios");require("@babel/runtime/helpers/typeof");var t=require("qs");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(e),a=r(t),o=function(){return o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},o.apply(this,arguments)};function c(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]])}return r}function i(e,t,r,n){return new(r||(r=Promise))((function(a,o){function c(e){try{u(n.next(e))}catch(e){o(e)}}function i(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(c,i)}u((n=n.apply(e,t||[])).next())}))}function u(e,t){var r,n,a,o,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(i){return function(u){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(c=0)),c;)try{if(r=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return c.label++,{value:i[1],done:!1};case 5:c.label++,n=i[1],i=[0];continue;case 7:i=c.ops.pop(),c.trys.pop();continue;default:if(!(a=c.trys,(a=a.length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){c=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){c.label=i[1];break}if(6===i[0]&&c.label<a[1]){c.label=a[1],a=i;break}if(a&&c.label<a[2]){c.label=a[2],c.ops.push(i);break}a[2]&&c.ops.pop(),c.trys.pop();continue}i=t.call(e,c)}catch(e){i=[6,e],n=0}finally{r=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function l(e){var t;"object"==typeof e&&null!==e?Array.isArray(e)?(t=[],e.forEach((function(e){return t.push(l(e))}))):(t={},Object.keys(e).forEach((function(r){t[r]=l(e[r])}))):t=e;return t}var s={},f=[];function d(t){return new Promise((function(r,n){var a,i={},u=!1,d=null,p=t.headers,y=t.data,v=t.params;t.url,t.timeout,t.method;var h=c(t,["headers","data","params","url","timeout","method"]),b=l(p);delete b.Referer,i.header=b;var m,w,E=y||v;if(i.data=l(E),i.url=(m=t.baseURL||"",w=t.url||"",m&&!/^([a-z][a-z\d+-.]*:)?\/\//i.test(w)?function(e,t){return t?"".concat(e.replace(/\/+$/,""),"/").concat(t.replace(/^\/+/,"")):e}(m,w):w),i.timeout=t.timeout,i.method=null===(a=null==t?void 0:t.method)||void 0===a?void 0:a.toUpperCase(),(i=o(o({},i),h)).success=function(a){var u={},l=a.data,s=a.statusCode,f=a.header,p=c(a,["data","statusCode","header"]);u.data=l,u.status=s,u.headers=f,u.config=t;var y=(u=o(o({},u),p)).config.validateStatus;if(u.status&&y&&!y(u.status)){var v="Request failed with status code ".concat(u.status);n(new e.AxiosError(v,"",i,d,u))}else r(u)},i.fail=function(t){u&&n(new e.AxiosError(t.errMsg,e.AxiosError.ERR_CANCELED,i,d)),n(new e.AxiosError(t.errMsg,t.errno,i,d))},f.includes(i.cancelKey))return n(new e.AxiosError("请求在发出之前被主动取消!",e.AxiosError.ERR_CANCELED,i,d)),void f.splice(f.indexOf(i.cancelKey),1);d=wx.request(i),void 0===i.signal&&i.cancelKey&&(s[i.cancelKey]=function(){u=!0,d.abort.call(d),Reflect.deleteProperty(s,i.cancelKey)})}))}function p(e,t){var r=o(o({},e.$options),t),n=r.headers,i=void 0===n?{}:n,u=r.sendFormData,l=void 0!==u&&u,s=r.data,f=void 0===s?void 0:s,d=r.params,p=void 0===d?{}:d,y=r.baseUrl,v=void 0===y?"":y,h=r.baseURL,b=void 0===h?"":h,m=c(r,["headers","sendFormData","data","params","baseUrl","baseURL"]),w=i["content-type"]||i["Content-Type"]||"application/json";i["content-type"]=l?"application/x-www-form-urlencoded":w;var E=l&&"object"==typeof f&&null!==f?a.default.stringify(f):f,x=v||b||e.$baseUrl;return o({headers:i,params:p,data:E,baseURL:x},m)}var y={query:"GET",create:"POST",putWay:"PUT",deletes:"DELETE",patchWay:"PATCH"},v=function(e,t){return function(r,n){return void 0===n&&(n={}),function(a,c){var i=c?"".concat(r,"/").concat(c):r;c&&console.warn("业务代码中拼接url发送请求的方式即将废弃,请使用ajax.".concat(y[t].toLocaleLowerCase(),"接口替换。相关url:").concat(i));var u="GET"===y[t]?[a,void 0]:[void 0,a],l=u[0],s=u[1],f=p(e,o(o({},n),{url:i,params:l,data:s,method:y[t]})),d=o(o({},f),{custom:o(o({},e.$options),f)});return e.request(d)}}};var h=["PUT","POST","DELETE","PATCH"];module.exports=function(e){var t={};t.$options=e;var r,a,c,l=t.$options.adapter||("undefined"!=typeof wx&&"function"==typeof wx.request?d:void 0);return t.$options.adapter=l,t.$engine=n.default.create(),["POST","PUT","PATCH","DELETE","GET","HEAD"].forEach((function(e){t[e.toLocaleLowerCase()]=function(e,t){return function(r,n){return function(a,c){return i(void 0,void 0,void 0,(function(){var i,l,s,d,y,v;return u(this,(function(u){switch(u.label){case 0:return i=o(o({},n),c),l=h.includes(t),s=o(o({},i),{params:l?void 0:a,data:l?a:void 0,url:r,method:t}),void 0!==i.cancelKey&&("undefined"!=typeof AbortController?(d=new AbortController,s.signal=d.signal,e.canceller[i.cancelKey]=function(){d.abort.call(d),Reflect.deleteProperty(e.canceller,i.cancelKey)}):(s.signal=void 0,e.canceller[i.cancelKey]=function(){f.push(i.cancelKey),Reflect.deleteProperty(e.canceller,i.cancelKey)})),y=p(e,s),(v=y.mock)?[2,Promise.resolve(v)]:[4,e.request(y)];case 1:return[2,u.sent()]}}))}))}}}(t,e)})),t.canceller=s,r=t,a=t.$engine,["request","interceptors"].forEach((function(e){Object.defineProperty(r,e,{value:a[e],writable:!1})})),(c=t).query=v(c,"query"),c.create=v(c,"create"),c.deletes=v(c,"deletes"),c.putWay=v(c,"putWay"),c.patchWay=v(c,"patchWay"),function(e){e.extend=function(t){Object.keys(t).forEach((function(r){e[r]=t[r]}))}}(t),t};
|
package/lib/ajax.esm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e,{AxiosError as t}from"axios";import"@babel/runtime/helpers/esm/typeof";import n from"qs";var r=function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},r.apply(this,arguments)};function a(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}function o(e,t,n,r){return new(n||(n=Promise))((function(a,o){function c(e){try{u(r.next(e))}catch(e){o(e)}}function i(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,i)}u((r=r.apply(e,t||[])).next())}))}function c(e,t){var n,r,a,o,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(c=0)),c;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return c.label++,{value:i[1],done:!1};case 5:c.label++,r=i[1],i=[0];continue;case 7:i=c.ops.pop(),c.trys.pop();continue;default:if(!(a=c.trys,(a=a.length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){c=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){c.label=i[1];break}if(6===i[0]&&c.label<a[1]){c.label=a[1],a=i;break}if(a&&c.label<a[2]){c.label=a[2],c.ops.push(i);break}a[2]&&c.ops.pop(),c.trys.pop();continue}i=t.call(e,c)}catch(e){i=[6,e],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function i(e){var t;"object"==typeof e&&null!==e?Array.isArray(e)?(t=[],e.forEach((function(e){return t.push(i(e))}))):(t={},Object.keys(e).forEach((function(n){t[n]=i(e[n])}))):t=e;return t}var u={},l=[];function s(e){return new Promise((function(n,o){var c,s={},f=!1,d=null,p=e.headers,y=e.data,v=e.params;e.url,e.timeout,e.method;var h=a(e,["headers","data","params","url","timeout","method"]),b=i(p);delete b.Referer,s.header=b;var m,w,E=y||v;if(s.data=i(E),s.url=(m=e.baseURL||"",w=e.url||"",m&&!/^([a-z][a-z\d+-.]*:)?\/\//i.test(w)?function(e,t){return t?"".concat(e.replace(/\/+$/,""),"/").concat(t.replace(/^\/+/,"")):e}(m,w):w),s.timeout=e.timeout,s.method=null===(c=null==e?void 0:e.method)||void 0===c?void 0:c.toUpperCase(),(s=r(r({},s),h)).success=function(c){var i={},u=c.data,l=c.statusCode,f=c.header,p=a(c,["data","statusCode","header"]);i.data=u,i.status=l,i.headers=f,i.config=e;var y=(i=r(r({},i),p)).config.validateStatus;if(i.status&&y&&!y(i.status)){var v="Request failed with status code ".concat(i.status);o(new t(v,"",s,d,i))}else n(i)},s.fail=function(e){f&&o(new t(e.errMsg,t.ERR_CANCELED,s,d)),o(new t(e.errMsg,e.errno,s,d))},l.includes(s.cancelKey))return o(new t("请求在发出之前被主动取消!",t.ERR_CANCELED,s,d)),void l.splice(l.indexOf(s.cancelKey),1);d=wx.request(s),void 0===s.signal&&s.cancelKey&&(u[s.cancelKey]=function(){f=!0,d.abort.call(d),Reflect.deleteProperty(u,s.cancelKey)})}))}function f(e,t){var o=r(r({},e.$options),t),c=o.headers,i=void 0===c?{}:c,u=o.sendFormData,l=void 0!==u&&u,s=o.data,f=void 0===s?void 0:s,d=o.params,p=void 0===d?{}:d,y=o.baseUrl,v=void 0===y?"":y,h=o.baseURL,b=void 0===h?"":h,m=a(o,["headers","sendFormData","data","params","baseUrl","baseURL"]),w=i["content-type"]||i["Content-Type"]||"application/json";i["content-type"]=l?"application/x-www-form-urlencoded":w;var E=l&&"object"==typeof f&&null!==f?n.stringify(f):f,P=v||b||e.$baseUrl;return r({headers:i,params:p,data:E,baseURL:P},m)}var d={query:"GET",create:"POST",putWay:"PUT",deletes:"DELETE",patchWay:"PATCH"},p=function(e,t){return function(n,a){return void 0===a&&(a={}),function(o,c){var i=c?"".concat(n,"/").concat(c):n;c&&console.warn("业务代码中拼接url发送请求的方式即将废弃,请使用ajax.".concat(d[t].toLocaleLowerCase(),"接口替换。相关url:").concat(i));var u="GET"===d[t]?[o,void 0]:[void 0,o],l=u[0],s=u[1],p=f(e,r(r({},a),{url:i,params:l,data:s,method:d[t]})),y=r(r({},p),{custom:r(r({},e.$options),p)});return e.request(y)}}};var y=["PUT","POST","DELETE","PATCH"];function v(t){var n={};n.$options=t;var a=n.$options.adapter||("undefined"!=typeof wx&&"function"==typeof wx.request?s:void 0);n.$options.adapter=a,n.$engine=e.create();var i,d,v;return["POST","PUT","PATCH","DELETE","GET","HEAD"].forEach((function(e){n[e.toLocaleLowerCase()]=function(e,t){return function(n,a){return function(i,u){return o(void 0,void 0,void 0,(function(){var o,s,d,p,v,h;return c(this,(function(c){switch(c.label){case 0:return o=r(r({},a),u),s=y.includes(t),d=r(r({},o),{params:s?void 0:i,data:s?i:void 0,url:n,method:t}),void 0!==o.cancelKey&&("undefined"!=typeof AbortController?(p=new AbortController,d.signal=p.signal,e.canceller[o.cancelKey]=function(){p.abort.call(p),Reflect.deleteProperty(e.canceller,o.cancelKey)}):(d.signal=void 0,e.canceller[o.cancelKey]=function(){l.push(o.cancelKey),Reflect.deleteProperty(e.canceller,o.cancelKey)})),v=f(e,d),(h=v.mock)?[2,Promise.resolve(h)]:[4,e.request(v)];case 1:return[2,c.sent()]}}))}))}}}(n,e)})),n.canceller=u,i=n,d=n.$engine,["request","interceptors"].forEach((function(e){Object.defineProperty(i,e,{value:d[e],writable:!1})})),(v=n).query=p(v,"query"),v.create=p(v,"create"),v.deletes=p(v,"deletes"),v.putWay=p(v,"putWay"),v.patchWay=p(v,"patchWay"),function(e){e.extend=function(t){Object.keys(t).forEach((function(n){e[n]=t[n]}))}}(n),n}export{v as default};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { AjaxInstance, AjaxOption, AnyObj } from './types';
|
|
2
|
+
type OldAjaxMethods = 'query' | 'create' | 'deletes' | 'putWay' | 'patchWay';
|
|
3
|
+
export type CustomAjaxMethods<T extends Object, GDataShape extends AnyObj = any> = <DataType = GDataShape>(path: string, config?: Partial<AjaxOption | T>) => (data?: any, expend?: string) => Promise<DataType>;
|
|
4
|
+
export declare const generateCustomMethod: <T extends Object>(ctx: AjaxInstance, name: OldAjaxMethods) => CustomAjaxMethods<T, any>;
|
|
5
|
+
declare function addCompatibleMethods<CusOpts>(ctx: AjaxInstance): void;
|
|
6
|
+
export default addCompatibleMethods;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AjaxInstance, AnyObj, ProxyedAttrs } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* 标准化config配置,或根据配置项设置相关的参数
|
|
4
|
+
* 该函数返回的配置对象,应该完全符合axios的配置规范
|
|
5
|
+
* @param {*} config
|
|
6
|
+
*/
|
|
7
|
+
export declare function normalizeConfig(ctx: AjaxInstance, config: any): any;
|
|
8
|
+
export declare function addInstanceExtendMethod(ctx: any): void;
|
|
9
|
+
export declare function proxyAxiosMethods<S extends {
|
|
10
|
+
[K in ProxyedAttrs]: any;
|
|
11
|
+
}>(target: AnyObj, source: S): void;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { AjaxInstance, AjaxOption, AxiosMethods } from './types';
|
|
2
|
+
type AnyObject = Record<string, any>;
|
|
3
|
+
export interface RequestCreator<COPT extends AnyObject, GDataShape extends AnyObject = any> {
|
|
4
|
+
<DataType = GDataShape>(url: string, options?: Partial<AjaxOption | COPT>): {
|
|
5
|
+
(params?: AnyObject | null, opts?: Partial<AjaxOption | COPT>): Promise<DataType>;
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
export declare const generateMethod: <COPT extends AnyObject, GDataShape extends AnyObject = any>(ajax: AjaxInstance, method: AxiosMethods) => RequestCreator<COPT, GDataShape>;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { AxiosInstance, AxiosRequestConfig } from 'axios';
|
|
2
|
+
import { CustomAjaxMethods } from './compatibleMethods';
|
|
3
|
+
import { RequestCreator } from './methods';
|
|
4
|
+
export type AnyObj = Record<string, any>;
|
|
5
|
+
export interface AjaxOption extends AxiosRequestConfig {
|
|
6
|
+
/** 是否发送FormData数据,仅用于post类请求,为true则使用qs.stringify序列化数据 */
|
|
7
|
+
sendFormData?: boolean;
|
|
8
|
+
/** 当前请求的取消函数名称,使用ajax.canceller[cancelKey]()的方式调用 */
|
|
9
|
+
cancelKey?: string;
|
|
10
|
+
/** 如果有值,则请求直接resolve这个值,阻断请求发送。用于开发mock数据 */
|
|
11
|
+
mock?: any;
|
|
12
|
+
}
|
|
13
|
+
export type RequestMethods = 'get' | 'post' | 'patch' | 'put' | 'delete' | 'head' | 'options';
|
|
14
|
+
export type ProxyedAttrs = 'request' | 'interceptors';
|
|
15
|
+
export type CancellerType = {
|
|
16
|
+
[K: string]: () => void;
|
|
17
|
+
};
|
|
18
|
+
export interface AjaxInstance<CusOpt = {}, DataShape = any> extends Pick<AxiosInstance, ProxyedAttrs> {
|
|
19
|
+
/** @deprecated 即将废弃,请使用ajax.get方法替换 */
|
|
20
|
+
query: CustomAjaxMethods<CusOpt, DataShape>;
|
|
21
|
+
/** @deprecated 即将废弃,请使用ajax.post方法替换 */
|
|
22
|
+
create: CustomAjaxMethods<CusOpt, DataShape>;
|
|
23
|
+
/** @deprecated 即将废弃,请使用ajax.delete方法替换 */
|
|
24
|
+
deletes: CustomAjaxMethods<CusOpt, DataShape>;
|
|
25
|
+
/** @deprecated 即将废弃,请使用ajax.put方法替换 */
|
|
26
|
+
putWay: CustomAjaxMethods<CusOpt, DataShape>;
|
|
27
|
+
/** @deprecated 即将废弃,请使用ajax.patch方法替换 */
|
|
28
|
+
patchWay: CustomAjaxMethods<CusOpt, DataShape>;
|
|
29
|
+
head: RequestCreator<CusOpt, DataShape>;
|
|
30
|
+
get: RequestCreator<CusOpt, DataShape>;
|
|
31
|
+
post: RequestCreator<CusOpt, DataShape>;
|
|
32
|
+
put: RequestCreator<CusOpt, DataShape>;
|
|
33
|
+
delete: RequestCreator<CusOpt, DataShape>;
|
|
34
|
+
patch: RequestCreator<CusOpt, DataShape>;
|
|
35
|
+
canceller: CancellerType;
|
|
36
|
+
$baseUrl: string;
|
|
37
|
+
$options: AjaxOption;
|
|
38
|
+
$engine: AxiosInstance;
|
|
39
|
+
}
|
|
40
|
+
export type AxiosMethods = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' | 'HEAD';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function isAbsoluteURL(url: string): boolean;
|
|
2
|
+
export declare function combineURLs(baseURL: string, relativeURL?: string): string;
|
|
3
|
+
export declare function buildFullPath(baseURL: string, requestedURL: string): string;
|
|
4
|
+
type DeepCopy<T> = T extends object ? T extends Array<infer Item> ? DeepCopy<Item>[] : {
|
|
5
|
+
[K in keyof T]: T[K] extends object ? DeepCopy<T[K]> : T[K];
|
|
6
|
+
} : T;
|
|
7
|
+
export declare function deepCopy<T>(obj: T): DeepCopy<T>;
|
|
8
|
+
export declare function getType(obj: any): string;
|
|
9
|
+
export declare function isWxAppEnv(): boolean;
|
|
10
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lx-frontend/multi-ajax",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "一个规范Ajax使用的框架",
|
|
5
|
+
"author": "lichao.franklee <lichao.franklee@gmail.com>",
|
|
6
|
+
"homepage": "",
|
|
7
|
+
"license": "ISC",
|
|
8
|
+
"main": "lib/ajax.cjs.js",
|
|
9
|
+
"module": "lib/ajax.esm.js",
|
|
10
|
+
"typings": "lib/types",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git@gitlab.lixinio.com:frontend/lx-basic.git"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@babel/runtime": "^7.21.0",
|
|
17
|
+
"axios": "1.3.4",
|
|
18
|
+
"qs": "^6.10.1",
|
|
19
|
+
"resolve": "^1.22.1"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@babel/core": "^7.21.0",
|
|
23
|
+
"@babel/plugin-transform-runtime": "^7.21.0",
|
|
24
|
+
"@babel/preset-env": "^7.20.2",
|
|
25
|
+
"@rollup/plugin-babel": "^5.3.1",
|
|
26
|
+
"@rollup/plugin-commonjs": "^24.0.1",
|
|
27
|
+
"@rollup/plugin-json": "^4.1.0",
|
|
28
|
+
"@rollup/plugin-node-resolve": "^15.0.1",
|
|
29
|
+
"@rollup/plugin-terser": "^0.4.0",
|
|
30
|
+
"@rollup/plugin-typescript": "^11.0.0",
|
|
31
|
+
"copyfiles": "^2.4.1",
|
|
32
|
+
"rimraf": "^3.0.2",
|
|
33
|
+
"rollup": "^2.79.1",
|
|
34
|
+
"typescript": "^4.9.5"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build:cjs": "rollup --config build/rollup.config.cjs.js",
|
|
38
|
+
"build:esm": "rollup --config build/rollup.config.esm.js",
|
|
39
|
+
"build": "npm run clean && npm run build:cjs && npm run build:esm",
|
|
40
|
+
"copy:dts": "copyfiles -f src/*.d.ts lib",
|
|
41
|
+
"clean": "rimraf lib",
|
|
42
|
+
"postinstall": "node build/scripts/patch-axios-post-install.js"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { InternalAxiosRequestConfig, AxiosPromise, AxiosError } from 'axios';
|
|
2
|
+
import { buildFullPath, deepCopy } from '../utils';
|
|
3
|
+
import { canceller, cancellerCalled } from '../canceller'
|
|
4
|
+
|
|
5
|
+
declare const wx: any;
|
|
6
|
+
|
|
7
|
+
export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosPromise {
|
|
8
|
+
// adapter接受的config要完全符合axios的配置规范,然后在这里针对不同的引擎做个性化修改
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
let requestConfig = {} as any;
|
|
11
|
+
let isAborted = false
|
|
12
|
+
let requestTask: any = null
|
|
13
|
+
const {
|
|
14
|
+
headers,
|
|
15
|
+
data,
|
|
16
|
+
params,
|
|
17
|
+
url,
|
|
18
|
+
timeout,
|
|
19
|
+
method,
|
|
20
|
+
...rest
|
|
21
|
+
} = config;
|
|
22
|
+
|
|
23
|
+
const requestHeader = deepCopy(headers);
|
|
24
|
+
delete requestHeader.Referer; // 小程序文档,header中不能有Referer
|
|
25
|
+
requestConfig.header = requestHeader;
|
|
26
|
+
|
|
27
|
+
const requestData = data || params; // wx环境,不论get还是post,参数传递的属性名均为data
|
|
28
|
+
requestConfig.data = deepCopy(requestData);
|
|
29
|
+
requestConfig.url = buildFullPath(config.baseURL || '', config.url || '');
|
|
30
|
+
requestConfig.timeout = config.timeout;
|
|
31
|
+
requestConfig.method = config?.method?.toUpperCase();
|
|
32
|
+
requestConfig = { ...requestConfig, ...rest };
|
|
33
|
+
|
|
34
|
+
requestConfig.success = (res) => {
|
|
35
|
+
let response = {} as any;
|
|
36
|
+
const {
|
|
37
|
+
data: resData,
|
|
38
|
+
statusCode,
|
|
39
|
+
header,
|
|
40
|
+
...restRes
|
|
41
|
+
} = res;
|
|
42
|
+
response.data = resData;
|
|
43
|
+
response.status = statusCode;
|
|
44
|
+
response.headers = header;
|
|
45
|
+
response.config = config;
|
|
46
|
+
response = { ...response, ...restRes };
|
|
47
|
+
|
|
48
|
+
const { validateStatus } = response.config;
|
|
49
|
+
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
|
50
|
+
resolve(response);
|
|
51
|
+
} else {
|
|
52
|
+
const errMsg = `Request failed with status code ${response.status}`
|
|
53
|
+
|
|
54
|
+
reject(new AxiosError(errMsg, '', requestConfig, requestTask, response));
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
requestConfig.fail = (err) => {
|
|
59
|
+
if (isAborted) {
|
|
60
|
+
reject(new AxiosError(err.errMsg, AxiosError.ERR_CANCELED, requestConfig, requestTask))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
reject(new AxiosError(err.errMsg, err.errno, requestConfig, requestTask));
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// 判断是否已经调用了取消函数
|
|
67
|
+
if (cancellerCalled.includes(requestConfig.cancelKey)) {
|
|
68
|
+
// 已经调用过取消函数了,直接抛出错误即可
|
|
69
|
+
reject(new AxiosError('请求在发出之前被主动取消!', AxiosError.ERR_CANCELED, requestConfig, requestTask))
|
|
70
|
+
// 删除记录
|
|
71
|
+
cancellerCalled.splice(cancellerCalled.indexOf(requestConfig.cancelKey), 1)
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
requestTask = wx.request(requestConfig);
|
|
76
|
+
|
|
77
|
+
// 设置了cancelKey,但是环境不支持AbortController
|
|
78
|
+
if ('undefined' === typeof requestConfig.signal && requestConfig.cancelKey) {
|
|
79
|
+
canceller[requestConfig.cancelKey] = () => {
|
|
80
|
+
isAborted = true
|
|
81
|
+
requestTask.abort.call(requestTask)
|
|
82
|
+
Reflect.deleteProperty(canceller, requestConfig.cancelKey)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
package/src/canceller.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// 兼容以前的老项目写法
|
|
2
|
+
|
|
3
|
+
import { normalizeConfig } from './helpers'
|
|
4
|
+
import {
|
|
5
|
+
AjaxInstance, AjaxOption, AnyObj, AxiosMethods
|
|
6
|
+
} from './types'
|
|
7
|
+
|
|
8
|
+
type OldAjaxMethods = 'query' | 'create' | 'deletes' | 'putWay' | 'patchWay'
|
|
9
|
+
|
|
10
|
+
export type CustomAjaxMethods<T extends Object, GDataShape extends AnyObj = any> = <DataType = GDataShape>(path: string, config?: Partial<AjaxOption | T>) => (data?: any, expend?: string) => Promise<DataType>
|
|
11
|
+
|
|
12
|
+
type MethodMap = {
|
|
13
|
+
[k in OldAjaxMethods]: AxiosMethods
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const methodMap: MethodMap = {
|
|
17
|
+
query: 'GET',
|
|
18
|
+
create: 'POST',
|
|
19
|
+
putWay: 'PUT',
|
|
20
|
+
deletes: 'DELETE',
|
|
21
|
+
patchWay: 'PATCH'
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const generateCustomMethod = <T extends Object>(ctx: AjaxInstance, name: OldAjaxMethods): CustomAjaxMethods<T> => <DataType = any>(path: string, config: Partial<AjaxOption | T> = {}) => (data?: any, expand?: string) => {
|
|
25
|
+
const url = expand ? `${path}/${expand}` : path;
|
|
26
|
+
if (expand) {
|
|
27
|
+
// eslint-disable-next-line no-console
|
|
28
|
+
console.warn(`业务代码中拼接url发送请求的方式即将废弃,请使用ajax.${methodMap[name].toLocaleLowerCase()}接口替换。相关url:${url}`)
|
|
29
|
+
}
|
|
30
|
+
const [newParams, newData] = methodMap[name] === 'GET' ? [data, undefined] : [undefined, data]
|
|
31
|
+
const config1 = normalizeConfig(ctx, {
|
|
32
|
+
...config, url, params: newParams, data: newData, method: methodMap[name],
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const options = {
|
|
36
|
+
...config1,
|
|
37
|
+
custom: {
|
|
38
|
+
...ctx.$options,
|
|
39
|
+
...config1,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
return ctx.request<any, DataType>(options);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function addCompatibleMethods<CusOpts>(ctx: AjaxInstance) {
|
|
47
|
+
ctx.query = generateCustomMethod<CusOpts>(ctx, 'query');
|
|
48
|
+
ctx.create = generateCustomMethod<CusOpts>(ctx, 'create');
|
|
49
|
+
ctx.deletes = generateCustomMethod<CusOpts>(ctx, 'deletes');
|
|
50
|
+
ctx.putWay = generateCustomMethod<CusOpts>(ctx, 'putWay');
|
|
51
|
+
ctx.patchWay = generateCustomMethod<CusOpts>(ctx, 'patchWay');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export default addCompatibleMethods;
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import qs from 'qs'
|
|
2
|
+
import { AjaxInstance, AnyObj, ProxyedAttrs } from './types'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 标准化config配置,或根据配置项设置相关的参数
|
|
6
|
+
* 该函数返回的配置对象,应该完全符合axios的配置规范
|
|
7
|
+
* @param {*} config
|
|
8
|
+
*/
|
|
9
|
+
export function normalizeConfig(ctx: AjaxInstance, config) {
|
|
10
|
+
const {
|
|
11
|
+
headers = {}, sendFormData = false, data = undefined, params = {}, baseUrl = '', baseURL = '', ...rest
|
|
12
|
+
} = { ...ctx.$options, ...config };
|
|
13
|
+
// 数据格式为FormData,修改content-type头,以及修改data格式
|
|
14
|
+
const contentType = headers['content-type'] || headers['Content-Type'] || 'application/json';
|
|
15
|
+
headers['content-type'] = sendFormData ? 'application/x-www-form-urlencoded' : contentType;
|
|
16
|
+
const sendData = sendFormData && typeof data === 'object' && data !== null ? qs.stringify(data) : data;
|
|
17
|
+
|
|
18
|
+
// baseUrl,支持两种写法,且用户配置的baseUrl优先级最高
|
|
19
|
+
const bUrl = baseUrl || baseURL || ctx.$baseUrl;
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
headers, params, data: sendData, baseURL: bUrl, ...rest,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function addInstanceExtendMethod(ctx) {
|
|
27
|
+
const extend = (source: AnyObj) => {
|
|
28
|
+
Object.keys(source).forEach((key) => {
|
|
29
|
+
ctx[key] = source[key];
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
ctx.extend = extend;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function proxyAxiosMethods<S extends {[K in ProxyedAttrs]: any}>(target: AnyObj, source: S): void {
|
|
36
|
+
const methods: ProxyedAttrs[] = ['request', 'interceptors'];
|
|
37
|
+
// const methods: ProxyedAttrs[] = ['request', 'get', 'post', 'delete', 'head', 'options', 'put', 'patch', 'interceptors'];
|
|
38
|
+
|
|
39
|
+
methods.forEach((method) => {
|
|
40
|
+
Object.defineProperty(target, method, {
|
|
41
|
+
value: source[method],
|
|
42
|
+
writable: false,
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import axios from 'axios'
|
|
2
|
+
import { wxAdatper } from './adapters/index'
|
|
3
|
+
import addCompatibleMethods from './compatibleMethods'
|
|
4
|
+
import { addInstanceExtendMethod, proxyAxiosMethods } from './helpers'
|
|
5
|
+
import { generateMethod } from './methods'
|
|
6
|
+
import { AjaxInstance, AjaxOption, AxiosMethods } from './types'
|
|
7
|
+
import { canceller } from './canceller'
|
|
8
|
+
|
|
9
|
+
declare const wx: any;
|
|
10
|
+
|
|
11
|
+
function isWxapp(): boolean {
|
|
12
|
+
return typeof wx !== 'undefined' && typeof wx.request === 'function';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export default function initAjax<CusOpts, ResDataShape = any>(options: AjaxOption & CusOpts): AjaxInstance<CusOpts, ResDataShape> {
|
|
16
|
+
const ajax = {} as AjaxInstance<CusOpts>;
|
|
17
|
+
ajax.$options = options;
|
|
18
|
+
|
|
19
|
+
// 检测wx如果没有自定义的适配器,则使用默认适配器
|
|
20
|
+
const adapter = ajax.$options.adapter || (isWxapp() ? wxAdatper : undefined);
|
|
21
|
+
ajax.$options.adapter = adapter
|
|
22
|
+
ajax.$engine = axios.create();
|
|
23
|
+
|
|
24
|
+
const requestMethods: AxiosMethods[] = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET', 'HEAD']
|
|
25
|
+
requestMethods.forEach((name) => {
|
|
26
|
+
ajax[name.toLocaleLowerCase()] = generateMethod<CusOpts, ResDataShape>(ajax, name)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
ajax.canceller = canceller
|
|
30
|
+
// 把ajax实例上的'request', 'interceptors'方法代理到axios上去
|
|
31
|
+
proxyAxiosMethods(ajax, ajax.$engine);
|
|
32
|
+
|
|
33
|
+
addCompatibleMethods(ajax)
|
|
34
|
+
|
|
35
|
+
// 添加extend方法,用于扩展ajax实例
|
|
36
|
+
addInstanceExtendMethod(ajax);
|
|
37
|
+
|
|
38
|
+
return ajax;
|
|
39
|
+
}
|
package/src/methods.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { normalizeConfig } from './helpers'
|
|
2
|
+
import { AjaxInstance, AjaxOption, AxiosMethods } from './types'
|
|
3
|
+
import { cancellerCalled } from './canceller'
|
|
4
|
+
type AnyObject = Record<string, any>
|
|
5
|
+
|
|
6
|
+
// GDataShape通过initAjax的第二个泛型参数传入,单独的请求如果不传返回数据的类型,则默认使用GDataShape
|
|
7
|
+
// DataType通过ajax.get, ajax.post等方法的泛型参数传入,如果定义了这个参数,会将GDataShape覆盖
|
|
8
|
+
export interface RequestCreator<COPT extends AnyObject, GDataShape extends AnyObject = any> {
|
|
9
|
+
// request = ajax.get(url, options_1)
|
|
10
|
+
<DataType = GDataShape>(url: string, options?: Partial<AjaxOption | COPT>): {
|
|
11
|
+
// request(params, options_2)
|
|
12
|
+
(params?: AnyObject | null, opts?: Partial<AjaxOption | COPT>): Promise<DataType>
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const postLikeMethods = ['PUT', 'POST', 'DELETE' , 'PATCH']
|
|
17
|
+
export const generateMethod = <COPT extends AnyObject, GDataShape extends AnyObject = any>(ajax: AjaxInstance, method: AxiosMethods): RequestCreator<COPT, GDataShape> =>
|
|
18
|
+
/**
|
|
19
|
+
*
|
|
20
|
+
* @param url 完整的请求url链接
|
|
21
|
+
* @param options ajax配置
|
|
22
|
+
* @returns 返回一个发送请求的函数
|
|
23
|
+
*/
|
|
24
|
+
<DataType = GDataShape>(url: string, options?: Partial<AjaxOption | COPT>) =>
|
|
25
|
+
/**
|
|
26
|
+
* 发送请求
|
|
27
|
+
* @param params get类请求的url参数 or post类请求的请求体数据
|
|
28
|
+
* @param opts ajax参数,拥有最高优先级
|
|
29
|
+
* @returns 请求数据
|
|
30
|
+
*/
|
|
31
|
+
async (params?: AnyObject | null, opts?: Partial<AjaxOption | COPT>) => {
|
|
32
|
+
const mergedOptions = { ...options, ...opts }
|
|
33
|
+
|
|
34
|
+
const isPostLikeMethod = postLikeMethods.includes(method)
|
|
35
|
+
|
|
36
|
+
const config = {
|
|
37
|
+
...mergedOptions,
|
|
38
|
+
params: isPostLikeMethod ? undefined : params,
|
|
39
|
+
data: isPostLikeMethod ? params : undefined,
|
|
40
|
+
url,
|
|
41
|
+
method
|
|
42
|
+
} as any
|
|
43
|
+
|
|
44
|
+
// 处理取消请求逻辑
|
|
45
|
+
const needCancel = typeof mergedOptions.cancelKey !== 'undefined'
|
|
46
|
+
|
|
47
|
+
if (needCancel) {
|
|
48
|
+
if (typeof AbortController !== 'undefined') {
|
|
49
|
+
// 环境支持AbortController
|
|
50
|
+
const controller = new AbortController()
|
|
51
|
+
config.signal = controller.signal
|
|
52
|
+
ajax.canceller[mergedOptions.cancelKey] = () => {
|
|
53
|
+
controller.abort.call(controller)
|
|
54
|
+
// 删除挂载在ajax上的请求中断函数
|
|
55
|
+
Reflect.deleteProperty(ajax.canceller, mergedOptions.cancelKey)
|
|
56
|
+
}
|
|
57
|
+
} else {
|
|
58
|
+
// 环境如果不支持AbortController,取消函数挂载到ajax只能交给adapter里面去实现了
|
|
59
|
+
config.signal = undefined
|
|
60
|
+
// 默认的取消函数,因为异步的关系,逻辑可能还没走到adapter中去,取消函数就已经被调用了,此时取消函数还是undefined
|
|
61
|
+
// 默认函数将已经调用的取消函数名称记录下来,在adapter中走到发送请求的逻辑时,直接中断即可
|
|
62
|
+
ajax.canceller[mergedOptions.cancelKey] = () => {
|
|
63
|
+
cancellerCalled.push(mergedOptions.cancelKey)
|
|
64
|
+
Reflect.deleteProperty(ajax.canceller, mergedOptions.cancelKey)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const finalOpts = normalizeConfig(ajax, config)
|
|
70
|
+
|
|
71
|
+
// mock
|
|
72
|
+
const mock = finalOpts.mock
|
|
73
|
+
if (mock) {
|
|
74
|
+
return Promise.resolve(mock)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const res = await ajax.request<any, DataType>(finalOpts)
|
|
78
|
+
|
|
79
|
+
return res
|
|
80
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { AxiosInstance, AxiosRequestConfig } from 'axios'
|
|
2
|
+
import { CustomAjaxMethods } from './compatibleMethods'
|
|
3
|
+
import { RequestCreator } from './methods'
|
|
4
|
+
|
|
5
|
+
export type AnyObj = Record<string, any>
|
|
6
|
+
|
|
7
|
+
export interface AjaxOption extends AxiosRequestConfig {
|
|
8
|
+
/** 是否发送FormData数据,仅用于post类请求,为true则使用qs.stringify序列化数据 */
|
|
9
|
+
sendFormData?: boolean
|
|
10
|
+
/** 当前请求的取消函数名称,使用ajax.canceller[cancelKey]()的方式调用 */
|
|
11
|
+
cancelKey?: string
|
|
12
|
+
/** 如果有值,则请求直接resolve这个值,阻断请求发送。用于开发mock数据 */
|
|
13
|
+
mock?: any
|
|
14
|
+
// [k: string]: any
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type RequestMethods = 'get' | 'post' | 'patch' | 'put' | 'delete' | 'head' | 'options'
|
|
18
|
+
|
|
19
|
+
export type ProxyedAttrs = 'request' | 'interceptors'
|
|
20
|
+
|
|
21
|
+
export type CancellerType = {
|
|
22
|
+
[K: string]: () => void
|
|
23
|
+
}
|
|
24
|
+
export interface AjaxInstance<CusOpt = {}, DataShape = any> extends Pick<AxiosInstance, ProxyedAttrs> {
|
|
25
|
+
/** @deprecated 即将废弃,请使用ajax.get方法替换 */
|
|
26
|
+
query: CustomAjaxMethods<CusOpt, DataShape>
|
|
27
|
+
/** @deprecated 即将废弃,请使用ajax.post方法替换 */
|
|
28
|
+
create: CustomAjaxMethods<CusOpt, DataShape>
|
|
29
|
+
/** @deprecated 即将废弃,请使用ajax.delete方法替换 */
|
|
30
|
+
deletes: CustomAjaxMethods<CusOpt, DataShape>
|
|
31
|
+
/** @deprecated 即将废弃,请使用ajax.put方法替换 */
|
|
32
|
+
putWay: CustomAjaxMethods<CusOpt, DataShape>
|
|
33
|
+
/** @deprecated 即将废弃,请使用ajax.patch方法替换 */
|
|
34
|
+
patchWay: CustomAjaxMethods<CusOpt, DataShape>
|
|
35
|
+
head: RequestCreator<CusOpt, DataShape>
|
|
36
|
+
get: RequestCreator<CusOpt, DataShape>
|
|
37
|
+
post: RequestCreator<CusOpt, DataShape>
|
|
38
|
+
put: RequestCreator<CusOpt, DataShape>
|
|
39
|
+
delete: RequestCreator<CusOpt, DataShape>
|
|
40
|
+
patch: RequestCreator<CusOpt, DataShape>
|
|
41
|
+
canceller: CancellerType
|
|
42
|
+
$baseUrl: string
|
|
43
|
+
$options: AjaxOption
|
|
44
|
+
$engine: AxiosInstance
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type AxiosMethods = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' | 'HEAD'
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export function isAbsoluteURL(url: string) {
|
|
2
|
+
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
|
3
|
+
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
|
4
|
+
// by any combination of letters, digits, plus, period, or hyphen.
|
|
5
|
+
return /^([a-z][a-z\d+-.]*:)?\/\//i.test(url);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function combineURLs(baseURL: string, relativeURL?: string) {
|
|
9
|
+
return relativeURL
|
|
10
|
+
? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}`
|
|
11
|
+
: baseURL;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function buildFullPath(baseURL: string, requestedURL: string): string {
|
|
15
|
+
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
|
16
|
+
return combineURLs(baseURL, requestedURL);
|
|
17
|
+
}
|
|
18
|
+
return requestedURL;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type DeepCopy<T> = T extends object
|
|
22
|
+
? T extends Array<infer Item>
|
|
23
|
+
? DeepCopy<Item>[]
|
|
24
|
+
: {
|
|
25
|
+
[K in keyof T]: T[K] extends object
|
|
26
|
+
? DeepCopy<T[K]>
|
|
27
|
+
: T[K]
|
|
28
|
+
}
|
|
29
|
+
: T
|
|
30
|
+
|
|
31
|
+
export function deepCopy<T>(obj: T): DeepCopy<T> {
|
|
32
|
+
let target;
|
|
33
|
+
if (typeof obj === 'object' && obj !== null) {
|
|
34
|
+
const isArray = Array.isArray(obj);
|
|
35
|
+
if (isArray) {
|
|
36
|
+
target = [];
|
|
37
|
+
obj.forEach((elem) => target.push(deepCopy(elem)));
|
|
38
|
+
} else {
|
|
39
|
+
target = {};
|
|
40
|
+
Object.keys(obj).forEach((key) => {
|
|
41
|
+
target[key] = deepCopy(obj[key]);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
target = obj;
|
|
46
|
+
}
|
|
47
|
+
return target;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function getType(obj: any): string {
|
|
51
|
+
const type = typeof obj;
|
|
52
|
+
if (type !== 'object') return type;
|
|
53
|
+
|
|
54
|
+
return Object.prototype.toString.call(obj)
|
|
55
|
+
.replace(/^\[object\s+(\S+)\]$/, '$1')
|
|
56
|
+
.toLowerCase();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
declare const wx: any
|
|
60
|
+
export function isWxAppEnv() {
|
|
61
|
+
return typeof wx !== 'undefined' && typeof wx.request === 'function'
|
|
62
|
+
}
|