@alicloud/fetcher-jsonp 1.1.81 → 1.2.2

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/CHANGELOG.md CHANGED
@@ -1,6 +1,5 @@
1
- HISTORY
2
- ===
1
+ # CHANGELOG
3
2
 
4
- # 1.0.0 2020/11/30 @驳是
3
+ ## 1.0.0 2020/11/30 @驳是
5
4
 
6
5
  * 开源第一版
package/README.md CHANGED
@@ -1,5 +1,4 @@
1
- @alicloud/fetcher-jsonp
2
- ===
1
+ # @alicloud/fetcher-jsonp
3
2
 
4
3
  > `@alicloud/fetcher` 的底层 Promise 比较「纯」的 jsonp 实现,可以单独使用,返回为封装过的 `JsonResponse` 而非直接的数据。
5
4
 
@@ -7,13 +6,13 @@
7
6
 
8
7
  `url` 需要使用者来拼接参数(跟原生的 fetch 类似)。
9
8
 
10
- # INSTALL
9
+ ## INSTALL
11
10
 
12
- ```
11
+ ```shell
13
12
  tnpm i @alicloud/fetcher-jsonp -S
14
13
  ```
15
14
 
16
- # API
15
+ ## APIs
17
16
 
18
17
  ```typescript
19
18
  import jsonp, {
@@ -25,6 +24,37 @@ jsonp(url, {
25
24
  timeout, // 超时毫秒数,默认 5 秒(一般来说 JSONP 请求要求必须有超时时间)
26
25
  charset,
27
26
  jsonpCallback,
28
- jsonpCallbackFunction
27
+ jsonpCallbackFunction,
28
+ signal // 和 fetch 一致
29
29
  });
30
30
  ```
31
+
32
+ ## 如何 abort
33
+
34
+ 参考 <https://javascript.info/fetch-abort> <https://developer.mozilla.org/en-US/docs/Web/API/AbortController>
35
+
36
+ ```typescript
37
+ import jsonp from '@alicloud/fetcher-jsonp';
38
+
39
+ function getAbortSignal(): AbortSignal | undefined {
40
+ if (!window.AbortController) { // IE 下都不支持,请 if 保护
41
+ return;
42
+ }
43
+
44
+ const abortController = new AbortController();
45
+
46
+ setTimeout(() => { // 这里是模拟的,实际场景中不会用 setTimeout
47
+ abortController.abort(); // 只有第一次调用有效
48
+ }, 200);
49
+
50
+ return abortController.signal;
51
+ }
52
+
53
+ return jsonp(jsonpUrl, {
54
+ signal: getAbortSignal(),
55
+ timeout
56
+ }).then(response => response.json());
57
+ ```
58
+
59
+ 请求被 Abort 只是形式上的 Abort,就像 `timeout` 一样,请求最终还是会继续(即使 DOM script 已经被移除)。
60
+ Abort 后得到的错误和原生的 AbortError 类似,其 name 属性为 `AbortError`。
@@ -9,7 +9,7 @@ exports.default = clearCallbackFn;
9
9
  * 清除全局的方法
10
10
  */
11
11
  function clearCallbackFn(callbackName) {
12
- var win = window; // eslint-disable-line @typescript-eslint/no-explicit-any
12
+ var win = window;
13
13
 
14
14
  try {
15
15
  // IE8 throws exception when try to delete a property on window http://stackoverflow.com/a/1824228/751089
@@ -22,16 +22,15 @@ var _clearCallbackFn = _interopRequireDefault(require("./clear-callback-fn"));
22
22
  */
23
23
  function jsonp() {
24
24
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
25
-
26
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
27
- _ref$timeout = _ref.timeout,
28
- timeout = _ref$timeout === void 0 ? 5000 : _ref$timeout,
29
- charset = _ref.charset,
30
- _ref$jsonpCallback = _ref.jsonpCallback,
31
- jsonpCallback = _ref$jsonpCallback === void 0 ? 'callback' : _ref$jsonpCallback,
32
- _ref$jsonpCallbackFun = _ref.jsonpCallbackFunction,
33
- jsonpCallbackFunction = _ref$jsonpCallbackFun === void 0 ? (0, _generateCallbackName.default)() : _ref$jsonpCallbackFun;
34
-
25
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
26
+ var _options$timeout = options.timeout,
27
+ timeout = _options$timeout === void 0 ? 5000 : _options$timeout,
28
+ charset = options.charset,
29
+ _options$jsonpCallbac = options.jsonpCallback,
30
+ jsonpCallback = _options$jsonpCallbac === void 0 ? 'callback' : _options$jsonpCallbac,
31
+ _options$jsonpCallbac2 = options.jsonpCallbackFunction,
32
+ jsonpCallbackFunction = _options$jsonpCallbac2 === void 0 ? (0, _generateCallbackName.default)() : _options$jsonpCallbac2,
33
+ signal = options.signal;
35
34
  var scriptElement = document.createElement('script');
36
35
  var timeoutId;
37
36
  scriptElement.src = "".concat(url).concat(url.indexOf('?') < 0 ? '?' : '&').concat(jsonpCallback, "=").concat(jsonpCallbackFunction);
@@ -55,10 +54,29 @@ function jsonp() {
55
54
  timeoutId = undefined;
56
55
  }
57
56
  }
57
+ /**
58
+ * 当 abort 或 timeout 的时候,执行 cleanup,虽然 DOM 被移除了,但 JS 的加载还在继续,超时后还有可能加载完毕,
59
+ * 需要避免这种情况下抛错
60
+ */
61
+
62
+
63
+ function cleanupPrematurely() {
64
+ cleanup();
65
+
66
+ window[jsonpCallbackFunction] = function () {
67
+ return (0, _clearCallbackFn.default)(jsonpCallbackFunction);
68
+ };
69
+ }
58
70
 
59
71
  return new Promise(function (resolve, reject) {
60
- // create a callback function
72
+ var returned = false; // 异步事件 1:回调
73
+
61
74
  window[jsonpCallbackFunction] = function (result) {
75
+ if (returned) {
76
+ return;
77
+ }
78
+
79
+ returned = true;
62
80
  resolve({
63
81
  ok: true,
64
82
  url: url,
@@ -67,23 +85,43 @@ function jsonp() {
67
85
  }
68
86
  });
69
87
  cleanup();
70
- };
88
+ }; // 异步事件 2:超时
89
+
71
90
 
72
91
  if (timeout > 0) {
73
92
  timeoutId = window.setTimeout(function () {
74
- reject((0, _createError.default)(_const.EJsonpError.TIMEOUT, "JSONP timeout after ".concat(timeout, "ms")));
75
- cleanup(); // 虽然 DOM 被移除了,但 JS 的加载还在继续,超时后还有可能加载完毕,需要避免这种情况下抛错
76
- // 注意这行一定要放在 cleanup 之后
93
+ if (returned) {
94
+ return;
95
+ }
77
96
 
78
- window[jsonpCallbackFunction] = function () {
79
- return (0, _clearCallbackFn.default)(jsonpCallbackFunction);
80
- };
97
+ returned = true;
98
+ reject((0, _createError.default)(_const.EJsonpError.TIMEOUT, "JSONP timeout after ".concat(timeout, "ms, url = ").concat(url)));
99
+ cleanupPrematurely();
81
100
  }, timeout);
82
- } // Caught if got 404/500
101
+ } // 异步事件 3:abort,监听 signal 的 abort(和 fetch 一样)
102
+ // https://developer.mozilla.org/en-US/docs/Web/API/AbortController
103
+
104
+
105
+ if (signal) {
106
+ signal.addEventListener('abort', function () {
107
+ if (returned) {
108
+ return;
109
+ }
110
+
111
+ returned = true;
112
+ reject((0, _createError.default)('AbortError', "The JSONP was aborted, url = ".concat(url)));
113
+ cleanupPrematurely();
114
+ });
115
+ } // 异步事件 3:404/500 等
83
116
 
84
117
 
85
118
  scriptElement.onerror = function () {
86
- reject((0, _createError.default)(_const.EJsonpError.NETWORK, "jsonp('".concat(url, "') failed")));
119
+ if (returned) {
120
+ return;
121
+ }
122
+
123
+ returned = true;
124
+ reject((0, _createError.default)(_const.EJsonpError.NETWORK, "JSONP failed, url = ".concat(url)));
87
125
  cleanup();
88
126
  };
89
127
  });
@@ -2,7 +2,7 @@
2
2
  * 清除全局的方法
3
3
  */
4
4
  export default function clearCallbackFn(callbackName) {
5
- var win = window; // eslint-disable-line @typescript-eslint/no-explicit-any
5
+ var win = window;
6
6
 
7
7
  try {
8
8
  // IE8 throws exception when try to delete a property on window http://stackoverflow.com/a/1824228/751089
@@ -10,16 +10,15 @@ import clearCallbackFn from './clear-callback-fn';
10
10
 
11
11
  export default function jsonp() {
12
12
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
13
-
14
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
15
- _ref$timeout = _ref.timeout,
16
- timeout = _ref$timeout === void 0 ? 5000 : _ref$timeout,
17
- charset = _ref.charset,
18
- _ref$jsonpCallback = _ref.jsonpCallback,
19
- jsonpCallback = _ref$jsonpCallback === void 0 ? 'callback' : _ref$jsonpCallback,
20
- _ref$jsonpCallbackFun = _ref.jsonpCallbackFunction,
21
- jsonpCallbackFunction = _ref$jsonpCallbackFun === void 0 ? generateCallbackName() : _ref$jsonpCallbackFun;
22
-
13
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14
+ var _options$timeout = options.timeout,
15
+ timeout = _options$timeout === void 0 ? 5000 : _options$timeout,
16
+ charset = options.charset,
17
+ _options$jsonpCallbac = options.jsonpCallback,
18
+ jsonpCallback = _options$jsonpCallbac === void 0 ? 'callback' : _options$jsonpCallbac,
19
+ _options$jsonpCallbac2 = options.jsonpCallbackFunction,
20
+ jsonpCallbackFunction = _options$jsonpCallbac2 === void 0 ? generateCallbackName() : _options$jsonpCallbac2,
21
+ signal = options.signal;
23
22
  var scriptElement = document.createElement('script');
24
23
  var timeoutId;
25
24
  scriptElement.src = "".concat(url).concat(url.indexOf('?') < 0 ? '?' : '&').concat(jsonpCallback, "=").concat(jsonpCallbackFunction);
@@ -43,10 +42,29 @@ export default function jsonp() {
43
42
  timeoutId = undefined;
44
43
  }
45
44
  }
45
+ /**
46
+ * 当 abort 或 timeout 的时候,执行 cleanup,虽然 DOM 被移除了,但 JS 的加载还在继续,超时后还有可能加载完毕,
47
+ * 需要避免这种情况下抛错
48
+ */
49
+
50
+
51
+ function cleanupPrematurely() {
52
+ cleanup();
53
+
54
+ window[jsonpCallbackFunction] = function () {
55
+ return clearCallbackFn(jsonpCallbackFunction);
56
+ };
57
+ }
46
58
 
47
59
  return new Promise(function (resolve, reject) {
48
- // create a callback function
60
+ var returned = false; // 异步事件 1:回调
61
+
49
62
  window[jsonpCallbackFunction] = function (result) {
63
+ if (returned) {
64
+ return;
65
+ }
66
+
67
+ returned = true;
50
68
  resolve({
51
69
  ok: true,
52
70
  url: url,
@@ -55,23 +73,43 @@ export default function jsonp() {
55
73
  }
56
74
  });
57
75
  cleanup();
58
- };
76
+ }; // 异步事件 2:超时
77
+
59
78
 
60
79
  if (timeout > 0) {
61
80
  timeoutId = window.setTimeout(function () {
62
- reject(createError(EJsonpError.TIMEOUT, "JSONP timeout after ".concat(timeout, "ms")));
63
- cleanup(); // 虽然 DOM 被移除了,但 JS 的加载还在继续,超时后还有可能加载完毕,需要避免这种情况下抛错
64
- // 注意这行一定要放在 cleanup 之后
81
+ if (returned) {
82
+ return;
83
+ }
65
84
 
66
- window[jsonpCallbackFunction] = function () {
67
- return clearCallbackFn(jsonpCallbackFunction);
68
- };
85
+ returned = true;
86
+ reject(createError(EJsonpError.TIMEOUT, "JSONP timeout after ".concat(timeout, "ms, url = ").concat(url)));
87
+ cleanupPrematurely();
69
88
  }, timeout);
70
- } // Caught if got 404/500
89
+ } // 异步事件 3:abort,监听 signal 的 abort(和 fetch 一样)
90
+ // https://developer.mozilla.org/en-US/docs/Web/API/AbortController
91
+
92
+
93
+ if (signal) {
94
+ signal.addEventListener('abort', function () {
95
+ if (returned) {
96
+ return;
97
+ }
98
+
99
+ returned = true;
100
+ reject(createError('AbortError', "The JSONP was aborted, url = ".concat(url)));
101
+ cleanupPrematurely();
102
+ });
103
+ } // 异步事件 3:404/500 等
71
104
 
72
105
 
73
106
  scriptElement.onerror = function () {
74
- reject(createError(EJsonpError.NETWORK, "jsonp('".concat(url, "') failed")));
107
+ if (returned) {
108
+ return;
109
+ }
110
+
111
+ returned = true;
112
+ reject(createError(EJsonpError.NETWORK, "JSONP failed, url = ".concat(url)));
75
113
  cleanup();
76
114
  };
77
115
  });
@@ -4,8 +4,19 @@
4
4
  export interface IJsonpOptions {
5
5
  timeout?: number;
6
6
  charset?: string;
7
+ /**
8
+ * 与服务端的参数名协议,告诉服务端,当你接收到参数名为此配置值的时候,需要返回 JSONP 格式,默认为 callback
9
+ */
7
10
  jsonpCallback?: string;
11
+ /**
12
+ * 通常 jsonpCallback 配置值对应的方法是自动创建的,它会放在 window 下,如果你需要自己指定方法,可以用它,
13
+ * 但必须自己保证可以通过 `window[此配置值]` 访问到它
14
+ */
8
15
  jsonpCallbackFunction?: string;
16
+ /**
17
+ * 让 JSONP 得以 abort,和 fetch 类型一致
18
+ */
19
+ signal?: AbortSignal | null;
9
20
  }
10
21
  /**
11
22
  * 模仿 Response 对象,fetch 的 Response 对象包含如下属性
@@ -21,7 +32,7 @@ export interface IJsonpOptions {
21
32
  * - json(): Promise<any>;
22
33
  */
23
34
  export interface IJsonpResponse<T = void> {
24
- ok: boolean;
35
+ ok: true;
25
36
  url: string;
26
37
  json(): Promise<T>;
27
38
  }
@@ -1,2 +1,2 @@
1
1
  import { EJsonpError } from '../const';
2
- export default function createError(name: EJsonpError, message: string): Error;
2
+ export default function createError(name: EJsonpError | 'AbortError', message: string): Error;
@@ -4,4 +4,4 @@ import { IJsonpOptions, IJsonpResponse } from '../types';
4
4
  *
5
5
  * 参考 https://github.com/camsong/fetch-jsonp
6
6
  */
7
- export default function jsonp<T = void>(url?: string, { timeout, charset, jsonpCallback, jsonpCallbackFunction }?: IJsonpOptions): Promise<IJsonpResponse<T>>;
7
+ export default function jsonp<T = void>(url?: string, options?: IJsonpOptions): Promise<IJsonpResponse<T>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alicloud/fetcher-jsonp",
3
- "version": "1.1.81",
3
+ "version": "1.2.2",
4
4
  "description": "fetcher 的底层 jsonp 实现,可独立使用",
5
5
  "license": "MIT",
6
6
  "sideEffects": false,
@@ -26,11 +26,12 @@
26
26
  ],
27
27
  "devDependencies": {
28
28
  "@alicloud/console-toolkit-cli": "^1.2.30",
29
- "@alicloud/console-toolkit-preset-component": "^1.2.32",
30
- "@alicloud/fetcher-demo-helpers": "^1.1.80",
31
- "@types/react": "^17.0.30",
29
+ "@alicloud/console-toolkit-preset-component": "^1.2.58",
30
+ "@alicloud/demo-rc-elements": "^1.5.5",
31
+ "@alicloud/fetcher-demo-helpers": "^1.1.81",
32
+ "@types/react": "^17.0.45",
32
33
  "react": "^17.0.2",
33
- "typescript": "^4.4.4"
34
+ "typescript": "^4.7.3"
34
35
  },
35
36
  "scripts": {
36
37
  "start": "breezr start-storybook",
@@ -43,5 +44,5 @@
43
44
  "clean": "rm -rf build",
44
45
  "prepublishOnly": "yarn clean && yarn build"
45
46
  },
46
- "gitHead": "c34c19b55903df37810149470d8fbcb62eaae71f"
47
+ "gitHead": "4c525e7246a8cdf73f3b431250125308f11d4151"
47
48
  }