@lx-frontend/multi-ajax 0.1.1 → 0.2.0

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.
Files changed (64) hide show
  1. package/README.md +10 -2
  2. package/__mocks__/axios.ts +49 -0
  3. package/jest.config.ts +24 -0
  4. package/lib/adapters/index.js +7 -0
  5. package/lib/adapters/index.js.map +1 -0
  6. package/lib/adapters/wx-adapter.d.ts +6 -0
  7. package/lib/adapters/wx-adapter.js +81 -0
  8. package/lib/adapters/wx-adapter.js.map +1 -0
  9. package/lib/cancelLastSameRequest.d.ts +9 -0
  10. package/lib/cancelLastSameRequest.js +48 -0
  11. package/lib/cancelLastSameRequest.js.map +1 -0
  12. package/lib/canceller.d.ts +2 -0
  13. package/lib/canceller.js +8 -0
  14. package/lib/canceller.js.map +1 -0
  15. package/lib/compatibleMethods.d.ts +6 -0
  16. package/lib/compatibleMethods.js +60 -0
  17. package/lib/compatibleMethods.js.map +1 -0
  18. package/lib/duplicateRequestPrevent.d.ts +5 -0
  19. package/lib/duplicateRequestPrevent.js +28 -0
  20. package/lib/duplicateRequestPrevent.js.map +1 -0
  21. package/lib/{types/helpers.d.ts → helpers.d.ts} +2 -2
  22. package/lib/helpers.js +42 -0
  23. package/lib/helpers.js.map +1 -0
  24. package/lib/index.d.ts +2 -0
  25. package/lib/index.js +34 -0
  26. package/lib/index.js.map +1 -0
  27. package/lib/methods.d.ts +7 -0
  28. package/lib/methods.js +107 -0
  29. package/lib/methods.js.map +1 -0
  30. package/lib/{types/types.d.ts → types.d.ts} +6 -5
  31. package/lib/types.js +3 -0
  32. package/lib/types.js.map +1 -0
  33. package/lib/{types/utils.d.ts → utils.d.ts} +13 -1
  34. package/lib/utils.js +66 -0
  35. package/lib/utils.js.map +1 -0
  36. package/package.json +14 -22
  37. package/src/adapters/wx-adapter.ts +35 -10
  38. package/src/cancelLastSameRequest.ts +43 -0
  39. package/src/canceller.ts +2 -2
  40. package/src/compatibleMethods.ts +24 -6
  41. package/src/duplicateRequestPrevent.ts +23 -0
  42. package/src/helpers.ts +3 -3
  43. package/src/index.ts +4 -3
  44. package/src/methods.ts +80 -37
  45. package/src/types.ts +7 -6
  46. package/src/utils.ts +28 -6
  47. package/tests/duplicateRequestPrevent.test.ts +39 -0
  48. package/tests/helpers.test.ts +73 -0
  49. package/tests/index.test.ts +657 -0
  50. package/tests/jest-setup.ts +4 -0
  51. package/tests/utils.test.ts +68 -0
  52. package/tsconfig.json +2 -1
  53. package/.babelrc.json +0 -5
  54. package/__tests__/lx-frontend-ajax.test.js +0 -7
  55. package/build/rollup.config.cjs.js +0 -43
  56. package/build/rollup.config.esm.js +0 -40
  57. package/lib/ajax.cjs.js +0 -1
  58. package/lib/ajax.esm.js +0 -1
  59. package/lib/types/adapters/wx-adapter.d.ts +0 -2
  60. package/lib/types/canceller.d.ts +0 -2
  61. package/lib/types/compatibleMethods.d.ts +0 -6
  62. package/lib/types/index.d.ts +0 -2
  63. package/lib/types/methods.d.ts +0 -9
  64. /package/lib/{types/adapters → adapters}/index.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"methods.js","sourceRoot":"","sources":["../src/methods.ts"],"names":[],"mappings":";;;;AAAA,qCAA2C;AAE3C,yCAAwD;AACxD,iCAA6C;AAC7C,qEAA8H;AAC9H,iEAA+F;AAY/F,IAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAG,OAAO,CAAC,CAAA;AACpD,IAAM,cAAc,GAAG,UAA4D,IAAwB,EAAE,MAAoB;IACtI;;;;;OAKG;IACH,OAAA,UAAwB,GAAW,EAAE,OAAoC;QACvE;;;;;WAKG;QACH,OAAA,UAAO,MAAsB,EAAE,IAAiC;;;;;wBACxD,aAAa,yCAAQ,OAAO,GAAK,IAAI,CAAE,CAAA;wBACvC,gBAAgB,GAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;wBAEpD,MAAM,GAAG,sCACV,aAAa,K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;;;;aAE/B;IA1FD,CA0FC;AAjGH,CAiGG,CAAA;AAxGQ,QAAA,cAAc,kBAwGtB"}
@@ -1,6 +1,6 @@
1
- import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import { CustomAjaxMethods } from './compatibleMethods';
3
- import { RequestCreator } from './methods';
1
+ import type { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import type { CustomAjaxMethods } from './compatibleMethods';
3
+ import type { RequestCreator } from './methods';
4
4
  export type AnyObj = Record<string, any>;
5
5
  export interface AjaxOption extends AxiosRequestConfig {
6
6
  /** 是否发送FormData数据,仅用于post类请求,为true则使用qs.stringify序列化数据 */
@@ -9,13 +9,14 @@ export interface AjaxOption extends AxiosRequestConfig {
9
9
  cancelKey?: string;
10
10
  /** 如果有值,则请求直接resolve这个值,阻断请求发送。用于开发mock数据 */
11
11
  mock?: any;
12
+ cancelLastSameUrl?: boolean;
12
13
  }
13
- export type RequestMethods = 'get' | 'post' | 'patch' | 'put' | 'delete' | 'head' | 'options';
14
+ export type RequestMethods = 'get' | 'post' | 'patch' | 'put' | 'delete' | 'head';
14
15
  export type ProxyedAttrs = 'request' | 'interceptors';
15
16
  export type CancellerType = {
16
17
  [K: string]: () => void;
17
18
  };
18
- export interface AjaxInstance<CusOpt = {}, DataShape = any> extends Pick<AxiosInstance, ProxyedAttrs> {
19
+ export interface AjaxInstance<CusOpt extends Object = {}, DataShape extends Object = any> extends Pick<AxiosInstance, ProxyedAttrs> {
19
20
  /** @deprecated 即将废弃,请使用ajax.get方法替换 */
20
21
  query: CustomAjaxMethods<CusOpt, DataShape>;
21
22
  /** @deprecated 即将废弃,请使用ajax.post方法替换 */
package/lib/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -6,5 +6,17 @@ type DeepCopy<T> = T extends object ? T extends Array<infer Item> ? DeepCopy<Ite
6
6
  } : T;
7
7
  export declare function deepCopy<T>(obj: T): DeepCopy<T>;
8
8
  export declare function getType(obj: any): string;
9
- export declare function isWxAppEnv(): boolean;
9
+ type NormalizedConfig = {
10
+ params?: Record<string, any>;
11
+ data?: Record<string, any>;
12
+ url?: string;
13
+ baseURL?: string;
14
+ method?: string;
15
+ };
16
+ /**
17
+ * 获取请求的标识,相同的请求配置有相同的标识
18
+ * @param config 经过标准化的ajax请求配置
19
+ * @returns 该请求的hash key
20
+ */
21
+ export declare function generateRequestHash(config: NormalizedConfig): string;
10
22
  export {};
package/lib/utils.js ADDED
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateRequestHash = exports.getType = exports.deepCopy = exports.buildFullPath = exports.combineURLs = exports.isAbsoluteURL = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var object_hash_1 = tslib_1.__importDefault(require("object-hash"));
6
+ function isAbsoluteURL(url) {
7
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
8
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
9
+ // by any combination of letters, digits, plus, period, or hyphen.
10
+ return /^([a-z][a-z\d+-.]*:)?\/\//i.test(url);
11
+ }
12
+ exports.isAbsoluteURL = isAbsoluteURL;
13
+ function combineURLs(baseURL, relativeURL) {
14
+ return relativeURL
15
+ ? "".concat(baseURL.replace(/\/+$/, ''), "/").concat(relativeURL.replace(/^\/+/, ''))
16
+ : baseURL;
17
+ }
18
+ exports.combineURLs = combineURLs;
19
+ function buildFullPath(baseURL, requestedURL) {
20
+ if (baseURL && !isAbsoluteURL(requestedURL)) {
21
+ return combineURLs(baseURL, requestedURL);
22
+ }
23
+ return requestedURL;
24
+ }
25
+ exports.buildFullPath = buildFullPath;
26
+ function deepCopy(obj) {
27
+ var target;
28
+ if (typeof obj === 'object' && obj !== null) {
29
+ if (Array.isArray(obj)) {
30
+ target = [];
31
+ obj.forEach(function (elem) { return target.push(deepCopy(elem)); });
32
+ }
33
+ else {
34
+ target = {};
35
+ Object.keys(obj).forEach(function (key) {
36
+ // @ts-ignore
37
+ target[key] = deepCopy(obj[key]);
38
+ });
39
+ }
40
+ }
41
+ else {
42
+ target = obj;
43
+ }
44
+ return target;
45
+ }
46
+ exports.deepCopy = deepCopy;
47
+ function getType(obj) {
48
+ var type = typeof obj;
49
+ if (type !== 'object')
50
+ return type;
51
+ return Object.prototype.toString.call(obj)
52
+ .replace(/^\[object\s+(\S+)\]$/, '$1')
53
+ .toLowerCase();
54
+ }
55
+ exports.getType = getType;
56
+ /**
57
+ * 获取请求的标识,相同的请求配置有相同的标识
58
+ * @param config 经过标准化的ajax请求配置
59
+ * @returns 该请求的hash key
60
+ */
61
+ function generateRequestHash(config) {
62
+ var _a = config.url, url = _a === void 0 ? '' : _a, _b = config.method, method = _b === void 0 ? '' : _b, _c = config.params, params = _c === void 0 ? {} : _c, _d = config.data, data = _d === void 0 ? {} : _d, _e = config.baseURL, baseURL = _e === void 0 ? '' : _e;
63
+ return (0, object_hash_1.default)(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, params), data), { baseURL: baseURL, url: url, method: method }));
64
+ }
65
+ exports.generateRequestHash = generateRequestHash;
66
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;AAAA,oEAA8B;AAE9B,SAAgB,aAAa,CAAC,GAAW;IACvC,gGAAgG;IAChG,gGAAgG;IAChG,kEAAkE;IAClE,OAAO,4BAA4B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC;AALD,sCAKC;AAED,SAAgB,WAAW,CAAC,OAAe,EAAE,WAAoB;IAC/D,OAAO,WAAW;QAChB,CAAC,CAAC,UAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE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O,CAAC,sBAAsB,EAAE,IAAI,CAAC;SACrC,WAAW,EAAE,CAAC;AACnB,CAAC;AAPD,0BAOC;AAWD;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,MAAwB;IAClD,IAAA,KAAgE,MAAM,IAA9D,EAAR,GAAG,mBAAG,EAAE,KAAA,EAAE,KAAsD,MAAM,OAAjD,EAAX,MAAM,mBAAG,EAAE,KAAA,EAAE,KAAyC,MAAM,OAApC,EAAX,MAAM,mBAAG,EAAE,KAAA,EAAE,KAA4B,MAAM,KAAzB,EAAT,IAAI,mBAAG,EAAE,KAAA,EAAE,KAAiB,MAAM,QAAX,EAAZ,OAAO,mBAAG,EAAE,KAAA,CAAW;IAC9E,OAAO,IAAA,qBAAI,yDACN,MAAM,GACN,IAAI,KACP,OAAO,SAAA,EACP,GAAG,KAAA,EACH,MAAM,QAAA,IACN,CAAA;AACJ,CAAC;AATD,kDASC"}
package/package.json CHANGED
@@ -1,44 +1,36 @@
1
1
  {
2
2
  "name": "@lx-frontend/multi-ajax",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "一个规范Ajax使用的框架",
5
5
  "author": "lichao.franklee <lichao.franklee@gmail.com>",
6
6
  "homepage": "",
7
7
  "license": "ISC",
8
- "main": "lib/ajax.cjs.js",
9
- "module": "lib/ajax.esm.js",
10
- "typings": "lib/types",
8
+ "main": "./lib/index.js",
9
+ "typings": "./lib/index.d.ts",
11
10
  "repository": {
12
11
  "type": "git",
13
12
  "url": "git@gitlab.lixinio.com:frontend/lx-basic.git"
14
13
  },
15
14
  "dependencies": {
16
- "@babel/runtime": "^7.21.0",
17
15
  "axios": "1.3.4",
16
+ "object-hash": "^3.0.0",
18
17
  "qs": "^6.10.1",
19
- "resolve": "^1.22.1"
18
+ "resolve": "^1.22.2"
20
19
  },
21
20
  "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",
21
+ "@jest/globals": "^29.5.0",
22
+ "@types/object-hash": "^3.0.2",
23
+ "@types/qs": "^6.9.7",
24
+ "jest": "^29.5.0",
32
25
  "rimraf": "^3.0.2",
33
- "rollup": "^2.79.1",
34
26
  "typescript": "^4.9.5"
35
27
  },
36
28
  "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",
29
+ "build": "pnpm clean && tsc",
30
+ "build:test": "npm run build -- --sourceMap false --inlineSourceMap true",
41
31
  "clean": "rimraf lib",
42
- "postinstall": "node build/scripts/patch-axios-post-install.js"
32
+ "postinstall": "node build/scripts/patch-axios-post-install.js",
33
+ "clean:coverage": "rimraf coverage",
34
+ "test": "npm run clean:coverage && npm run build:test && jest"
43
35
  }
44
36
  }
@@ -1,9 +1,15 @@
1
1
  import { InternalAxiosRequestConfig, AxiosPromise, AxiosError } from 'axios';
2
- import { buildFullPath, deepCopy } from '../utils';
2
+ import { buildFullPath, deepCopy, generateRequestHash } from '../utils';
3
3
  import { canceller, cancellerCalled } from '../canceller'
4
+ import { addRequestCanceler, clearCancelerByHash } from '../cancelLastSameRequest'
4
5
 
5
6
  declare const wx: any;
6
7
 
8
+ type WxErr = {
9
+ errMsg: string;
10
+ errno: string;
11
+ }
12
+
7
13
  export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosPromise {
8
14
  // adapter接受的config要完全符合axios的配置规范,然后在这里针对不同的引擎做个性化修改
9
15
  return new Promise((resolve, reject) => {
@@ -20,6 +26,8 @@ export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosProm
20
26
  ...rest
21
27
  } = config;
22
28
 
29
+ const requestHash = generateRequestHash(config)
30
+
23
31
  const requestHeader = deepCopy(headers);
24
32
  delete requestHeader.Referer; // 小程序文档,header中不能有Referer
25
33
  requestConfig.header = requestHeader;
@@ -31,7 +39,7 @@ export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosProm
31
39
  requestConfig.method = config?.method?.toUpperCase();
32
40
  requestConfig = { ...requestConfig, ...rest };
33
41
 
34
- requestConfig.success = (res) => {
42
+ requestConfig.success = (res: any) => {
35
43
  let response = {} as any;
36
44
  const {
37
45
  data: resData,
@@ -46,16 +54,17 @@ export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosProm
46
54
  response = { ...response, ...restRes };
47
55
 
48
56
  const { validateStatus } = response.config;
57
+
49
58
  if (!response.status || !validateStatus || validateStatus(response.status)) {
50
59
  resolve(response);
51
60
  } else {
52
61
  const errMsg = `Request failed with status code ${response.status}`
53
-
54
62
  reject(new AxiosError(errMsg, '', requestConfig, requestTask, response));
55
63
  }
56
64
  };
57
65
 
58
- requestConfig.fail = (err) => {
66
+ requestConfig.fail = (err: WxErr) => {
67
+
59
68
  if (isAborted) {
60
69
  reject(new AxiosError(err.errMsg, AxiosError.ERR_CANCELED, requestConfig, requestTask))
61
70
  }
@@ -71,16 +80,32 @@ export default function wxAdapter(config: InternalAxiosRequestConfig): AxiosProm
71
80
  cancellerCalled.splice(cancellerCalled.indexOf(requestConfig.cancelKey), 1)
72
81
  return
73
82
  }
74
-
75
83
  requestTask = wx.request(requestConfig);
76
84
 
77
85
  // 设置了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)
86
+ if ('undefined' === typeof AbortController) {
87
+ if (requestConfig.cancelKey) {
88
+ canceller[requestConfig.cancelKey] = () => {
89
+ isAborted = true
90
+ requestTask.abort.call(requestTask)
91
+ Reflect.deleteProperty(canceller, requestConfig.cancelKey)
92
+ reject(new AxiosError('请求被取消!', AxiosError.ERR_CANCELED, requestConfig, requestTask))
93
+ }
94
+ }
95
+
96
+ if (requestConfig.cancelLastSameUrl && requestConfig.method.toLocaleLowerCase() === 'get') {
97
+ addRequestCanceler(
98
+ config.url as string,
99
+ requestHash,
100
+ () => {
101
+ isAborted = true
102
+ requestTask.abort.call(requestTask)
103
+ clearCancelerByHash(config.url as string, requestHash)
104
+ reject(new AxiosError('请求被取消!', AxiosError.ERR_CANCELED, requestConfig, requestTask))
105
+ }
106
+ )
83
107
  }
84
108
  }
85
109
  });
86
110
  }
111
+ wxAdapter.type = 'wx'
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 取消相同URL和method的上一个未结束请求,主要目的是防止页面切换时串数据,比如tab切换
3
+ * 且只针对get请求
4
+ */
5
+ // import hash from 'object-hash'
6
+ export { generateRequestHash } from "./utils"
7
+
8
+ const cancellerCache: Record<string, Record<string, any>> = {}
9
+
10
+ export function addRequestCanceler(url: string, hash: string, cancelFn: () => void) {
11
+ const urlCache = cancellerCache[url] || {}
12
+ urlCache[hash] = cancelFn
13
+ cancellerCache[url] = urlCache
14
+ }
15
+
16
+ export function clearCancelerByHash(url: string, hash: string) {
17
+ if (cancellerCache[url] && cancellerCache[url][hash]) {
18
+ Reflect.deleteProperty(cancellerCache[url], hash)
19
+ if (Object.keys(cancellerCache[url]).length === 0) {
20
+ Reflect.deleteProperty(cancellerCache, url)
21
+ }
22
+ }
23
+ }
24
+
25
+
26
+ export function checkIfHasURLCanceler(url: string): boolean {
27
+ if (!cancellerCache[url]) return false
28
+ if (Object.keys(cancellerCache[url]).length === 0) return false
29
+ return true
30
+ }
31
+
32
+ export function execCanceler(url: string) {
33
+ const cancelers = cancellerCache[url] || {}
34
+ Object.entries(cancelers).forEach(([key, fn]) => {
35
+ fn()
36
+ Reflect.deleteProperty(cancelers, key)
37
+ })
38
+ Reflect.deleteProperty(cancellerCache, url)
39
+ }
40
+
41
+ // export function getCachedCanceler(hashKey: string) {
42
+ // return cancellerCache[hashKey]
43
+ // }
package/src/canceller.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // 用来存储取消函数
2
- export const canceller = {}
2
+ export const canceller: Record<string, any> = {}
3
3
 
4
4
  // 用来存储已经被调用的取消函数名称
5
- export const cancellerCalled = []
5
+ export const cancellerCalled: string[] = []
@@ -1,13 +1,15 @@
1
1
  // 兼容以前的老项目写法
2
2
 
3
+ import { addPendingRequest, checkIfHasPendingRequest, clearPendingRequest, getCachedRequest } from './duplicateRequestPrevent'
3
4
  import { normalizeConfig } from './helpers'
4
- import {
5
+ import { generateRequestHash } from './utils'
6
+ import type {
5
7
  AjaxInstance, AjaxOption, AnyObj, AxiosMethods
6
8
  } from './types'
7
9
 
8
- type OldAjaxMethods = 'query' | 'create' | 'deletes' | 'putWay' | 'patchWay'
10
+ export type OldAjaxMethods = 'query' | 'create' | 'deletes' | 'putWay' | 'patchWay'
9
11
 
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>
12
+ 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
13
 
12
14
  type MethodMap = {
13
15
  [k in OldAjaxMethods]: AxiosMethods
@@ -21,7 +23,7 @@ const methodMap: MethodMap = {
21
23
  patchWay: 'PATCH'
22
24
  }
23
25
 
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) => {
26
+ export const generateCustomMethod = <T extends Object>(ctx: AjaxInstance<T>, name: OldAjaxMethods): CustomAjaxMethods<T> => <DataType = any>(path: string, config: Partial<AjaxOption | T> = {}) => async (data?: any, expand?: string) => {
25
27
  const url = expand ? `${path}/${expand}` : path;
26
28
  if (expand) {
27
29
  // eslint-disable-next-line no-console
@@ -40,10 +42,26 @@ export const generateCustomMethod = <T extends Object>(ctx: AjaxInstance, name:
40
42
  },
41
43
  };
42
44
 
43
- return ctx.request<any, DataType>(options);
45
+ const hashKey = generateRequestHash(config1)
46
+ if (checkIfHasPendingRequest(hashKey)) {
47
+ // 重复,且处于pending状态的请求,复用
48
+ return getCachedRequest(hashKey)
49
+ }
50
+
51
+ const request = ctx.request<any, DataType>(options);
52
+
53
+ // 缓存请求
54
+ addPendingRequest(hashKey, request)
55
+
56
+ const res = await request
57
+
58
+ // 清理缓存的请求
59
+ clearPendingRequest(hashKey)
60
+
61
+ return res
44
62
  };
45
63
 
46
- function addCompatibleMethods<CusOpts>(ctx: AjaxInstance) {
64
+ function addCompatibleMethods<CusOpts extends Object>(ctx: AjaxInstance<CusOpts>) {
47
65
  ctx.query = generateCustomMethod<CusOpts>(ctx, 'query');
48
66
  ctx.create = generateCustomMethod<CusOpts>(ctx, 'create');
49
67
  ctx.deletes = generateCustomMethod<CusOpts>(ctx, 'deletes');
@@ -0,0 +1,23 @@
1
+ export { generateRequestHash } from "./utils"
2
+
3
+ const pendingRequest: Record<string, any> = {}
4
+
5
+ export function addPendingRequest(hash: string, request: Promise<any>, timeout = 300) {
6
+ let timer
7
+ pendingRequest[hash] = request
8
+ timer = setTimeout(() => {
9
+ clearPendingRequest(hash)
10
+ }, timeout)
11
+ }
12
+
13
+ export function clearPendingRequest(hash: string) {
14
+ Reflect.deleteProperty(pendingRequest, hash)
15
+ }
16
+
17
+ export function checkIfHasPendingRequest(hashKey: string): boolean {
18
+ return Reflect.has(pendingRequest, hashKey)
19
+ }
20
+
21
+ export function getCachedRequest(hashKey: string) {
22
+ return pendingRequest[hashKey]
23
+ }
package/src/helpers.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import qs from 'qs'
2
- import { AjaxInstance, AnyObj, ProxyedAttrs } from './types'
2
+ import type { AjaxInstance, AnyObj, ProxyedAttrs } from './types'
3
3
 
4
4
  /**
5
5
  * 标准化config配置,或根据配置项设置相关的参数
6
6
  * 该函数返回的配置对象,应该完全符合axios的配置规范
7
7
  * @param {*} config
8
8
  */
9
- export function normalizeConfig(ctx: AjaxInstance, config) {
9
+ export function normalizeConfig<CusOpt extends Object>(ctx: AjaxInstance<CusOpt>, config: any) {
10
10
  const {
11
11
  headers = {}, sendFormData = false, data = undefined, params = {}, baseUrl = '', baseURL = '', ...rest
12
12
  } = { ...ctx.$options, ...config };
@@ -23,7 +23,7 @@ export function normalizeConfig(ctx: AjaxInstance, config) {
23
23
  };
24
24
  }
25
25
 
26
- export function addInstanceExtendMethod(ctx) {
26
+ export function addInstanceExtendMethod(ctx: any) {
27
27
  const extend = (source: AnyObj) => {
28
28
  Object.keys(source).forEach((key) => {
29
29
  ctx[key] = source[key];
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ import { wxAdatper } from './adapters/index'
3
3
  import addCompatibleMethods from './compatibleMethods'
4
4
  import { addInstanceExtendMethod, proxyAxiosMethods } from './helpers'
5
5
  import { generateMethod } from './methods'
6
- import { AjaxInstance, AjaxOption, AxiosMethods } from './types'
6
+ import type { AjaxInstance, AjaxOption, AxiosMethods } from './types'
7
7
  import { canceller } from './canceller'
8
8
 
9
9
  declare const wx: any;
@@ -12,7 +12,7 @@ function isWxapp(): boolean {
12
12
  return typeof wx !== 'undefined' && typeof wx.request === 'function';
13
13
  }
14
14
 
15
- export default function initAjax<CusOpts, ResDataShape = any>(options: AjaxOption & CusOpts): AjaxInstance<CusOpts, ResDataShape> {
15
+ export default function initAjax<CusOpts extends Object, ResDataShape extends Object = any>(options: AjaxOption & CusOpts): AjaxInstance<CusOpts, ResDataShape> {
16
16
  const ajax = {} as AjaxInstance<CusOpts>;
17
17
  ajax.$options = options;
18
18
 
@@ -22,7 +22,8 @@ export default function initAjax<CusOpts, ResDataShape = any>(options: AjaxOptio
22
22
  ajax.$engine = axios.create();
23
23
 
24
24
  const requestMethods: AxiosMethods[] = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET', 'HEAD']
25
- requestMethods.forEach((name) => {
25
+ requestMethods.forEach((name: AxiosMethods) => {
26
+ // @ts-ignore
26
27
  ajax[name.toLocaleLowerCase()] = generateMethod<CusOpts, ResDataShape>(ajax, name)
27
28
  })
28
29
 
package/src/methods.ts CHANGED
@@ -1,36 +1,37 @@
1
1
  import { normalizeConfig } from './helpers'
2
- import { AjaxInstance, AjaxOption, AxiosMethods } from './types'
3
- import { cancellerCalled } from './canceller'
4
- type AnyObject = Record<string, any>
2
+ import type { AjaxInstance, AjaxOption, AxiosMethods } from './types'
3
+ import { cancellerCalled, canceller } from './canceller'
4
+ import { generateRequestHash } from './utils'
5
+ import { addPendingRequest, checkIfHasPendingRequest, clearPendingRequest, getCachedRequest } from './duplicateRequestPrevent'
6
+ import { addRequestCanceler, clearCancelerByHash, execCanceler } from './cancelLastSameRequest'
5
7
 
6
8
  // GDataShape通过initAjax的第二个泛型参数传入,单独的请求如果不传返回数据的类型,则默认使用GDataShape
7
9
  // DataType通过ajax.get, ajax.post等方法的泛型参数传入,如果定义了这个参数,会将GDataShape覆盖
8
- export interface RequestCreator<COPT extends AnyObject, GDataShape extends AnyObject = any> {
10
+ export interface RequestCreator<COPT extends Object, GDataShape extends Object = any> {
9
11
  // request = ajax.get(url, options_1)
10
- <DataType = GDataShape>(url: string, options?: Partial<AjaxOption | COPT>): {
12
+ <DataType = GDataShape>(url: string, options?: Partial<AjaxOption & COPT>): {
11
13
  // request(params, options_2)
12
- (params?: AnyObject | null, opts?: Partial<AjaxOption | COPT>): Promise<DataType>
14
+ (params?: Object | null, opts?: Partial<AjaxOption & COPT>): Promise<DataType>
13
15
  }
14
16
  }
15
17
 
16
18
  const postLikeMethods = ['PUT', 'POST', 'DELETE' , 'PATCH']
17
- export const generateMethod = <COPT extends AnyObject, GDataShape extends AnyObject = any>(ajax: AjaxInstance, method: AxiosMethods): RequestCreator<COPT, GDataShape> =>
19
+ export const generateMethod = <COPT extends Object = {}, GDataShape extends Object = any>(ajax: AjaxInstance<COPT>, method: AxiosMethods): RequestCreator<COPT, GDataShape> =>
18
20
  /**
19
21
  *
20
22
  * @param url 完整的请求url链接
21
23
  * @param options ajax配置
22
24
  * @returns 返回一个发送请求的函数
23
25
  */
24
- <DataType = GDataShape>(url: string, options?: Partial<AjaxOption | COPT>) =>
26
+ <DataType = GDataShape>(url: string, options?: Partial<AjaxOption & COPT>) =>
25
27
  /**
26
28
  * 发送请求
27
29
  * @param params get类请求的url参数 or post类请求的请求体数据
28
30
  * @param opts ajax参数,拥有最高优先级
29
31
  * @returns 请求数据
30
32
  */
31
- async (params?: AnyObject | null, opts?: Partial<AjaxOption | COPT>) => {
33
+ async (params?: Object | null, opts?: Partial<AjaxOption & COPT>) => {
32
34
  const mergedOptions = { ...options, ...opts }
33
-
34
35
  const isPostLikeMethod = postLikeMethods.includes(method)
35
36
 
36
37
  const config = {
@@ -41,31 +42,6 @@ export const generateMethod = <COPT extends AnyObject, GDataShape extends AnyObj
41
42
  method
42
43
  } as any
43
44
 
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
45
  const finalOpts = normalizeConfig(ajax, config)
70
46
 
71
47
  // mock
@@ -74,7 +50,74 @@ export const generateMethod = <COPT extends AnyObject, GDataShape extends AnyObj
74
50
  return Promise.resolve(mock)
75
51
  }
76
52
 
77
- const res = await ajax.request<any, DataType>(finalOpts)
53
+ // 完全相同的请求,且都处于pending状态,复用上一个
54
+ const hashKey = generateRequestHash(finalOpts)
55
+ if (checkIfHasPendingRequest(hashKey)) {
56
+ // 重复,且处于pending状态的请求,复用
57
+ return getCachedRequest(hashKey)
58
+ }
59
+
60
+ // 这个检查应该位于前面复用请求的逻辑后面,不能乱序
61
+ // 如果需要取消之前处于pending状态相同url请求
62
+ if (finalOpts.cancelLastSameUrl) {
63
+ const currUrl = finalOpts.url
64
+ // 执行所有缓存的url相关的取消函数
65
+ execCanceler(currUrl)
66
+ }
67
+
68
+ // 缓存当前请求的取消函数
69
+ if (typeof AbortController !== 'undefined') {
70
+ // 环境支持AbortController
71
+ const controller = new AbortController()
72
+ finalOpts.signal = controller.signal
78
73
 
79
- return res
74
+ if (typeof mergedOptions.cancelKey !== 'undefined') {
75
+ ajax.canceller[mergedOptions.cancelKey as string] = () => {
76
+ controller.abort.call(controller)
77
+ // 删除挂载在ajax上的请求中断函数
78
+ Reflect.deleteProperty(ajax.canceller, mergedOptions.cancelKey as string)
79
+ }
80
+ }
81
+
82
+ // 缓存当前请求的取消函数,假如后续有相同的url请求需要取消该请求,可以通过这里缓存的函数实现(只针对get请求)
83
+ if (finalOpts.cancelLastSameUrl && finalOpts.method.toLocaleLowerCase() === 'get') {
84
+ addRequestCanceler(
85
+ finalOpts.url,
86
+ hashKey,
87
+ () => {
88
+ controller.abort.call(controller)
89
+ clearCancelerByHash(finalOpts.url, hashKey)
90
+ }
91
+ )
92
+ }
93
+ } else {
94
+ // 环境如果不支持AbortController,取消函数挂载到ajax只能交给adapter里面去实现了
95
+ finalOpts.signal = undefined
96
+ // 因为异步的关系(axios中发出请求之前,对拦截函数处理可能是异步的),逻辑可能还没走到adapter中去,取消函数就已经被调用了
97
+ // 此时取消函数还是undefined,所以这里提供默认取消函数
98
+
99
+ if (typeof mergedOptions.cancelKey !== 'undefined') {
100
+ ajax.canceller[mergedOptions.cancelKey as string] = () => {
101
+ // 默认函数将已经调用的取消函数名称记录下来,在adapter中走到发送请求的逻辑时,直接中断即可
102
+ cancellerCalled.push(mergedOptions.cancelKey as string)
103
+ Reflect.deleteProperty(ajax.canceller, mergedOptions.cancelKey as string)
104
+ }
105
+ }
106
+
107
+ }
108
+
109
+ try {
110
+ const request = ajax.request<any, DataType>(finalOpts)
111
+ addPendingRequest(hashKey, request)
112
+ return await request
113
+ } catch (e) {
114
+ return Promise.reject(e)
115
+ } finally {
116
+ // 请求成功,删除ajax.canceller上对应的取消函数
117
+ Reflect.deleteProperty(canceller, finalOpts.cancelKey)
118
+ // 删除用于取消相同URL请求功能而缓存的取消函数
119
+ clearCancelerByHash(finalOpts.url, hashKey)
120
+ // 删除缓存的请求(用于复用300ms内完全相同的多个请求)
121
+ clearPendingRequest(hashKey)
122
+ }
80
123
  }