@fatcherjs/middleware-aborter 2.0.0 → 3.0.0-alpha-5

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 fatcherjs
3
+ Copyright (c) 2022 Fansy
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,12 +1,4 @@
1
- # @fatcherjs/middleware-aborter
2
-
3
- A middleware for aborting fatcher request.
4
-
5
- [![codecov](https://codecov.io/gh/fatcherjs/middleware-aborter/branch/master/graph/badge.svg?token=TFKUGW6YNI)](https://codecov.io/gh/fatcherjs/middleware-aborter)
6
- [![install size](https://packagephobia.com/badge?p=@fatcherjs/middleware-aborter)](https://packagephobia.com/result?p=@fatcherjs/middleware-aborter)
7
- <a href="https://unpkg.com/@fatcherjs/middleware-aborter"><img alt="Size" src="https://img.badgesize.io/https://unpkg.com/@fatcherjs/middleware-aborter"></a>
8
- <a href="https://npmjs.com/package/@fatcherjs/middleware-aborter"><img src="https://img.shields.io/npm/v/@fatcherjs/middleware-aborter.svg" alt="npm package"></a>
9
- <a href="https://github.com/fatcherjs/middleware-aborter/actions/workflows/ci.yml"><img src="https://github.com/fatcherjs/middleware-aborter/actions/workflows/ci.yml/badge.svg?branch=master" alt="build status"></a>
1
+ # @fatcher/middleware-aborter
10
2
 
11
3
  ## Install
12
4
 
@@ -19,49 +11,56 @@ A middleware for aborting fatcher request.
19
11
  ### CDN
20
12
 
21
13
  ```html
22
- <script src="https://cdn.jsdelivr.net/npm/@fatcherjs/middleware-aborter/dist/aborter.min.js"></script>
14
+ <script src="https://cdn.jsdelivr.net/npm/@fatcherjs/middleware-aborter/dist/index.min.js"></script>
23
15
  ```
24
16
 
25
17
  ## Usage
26
18
 
27
19
  ```ts
28
- import { aborter, isAbortError } from '@fatcherjs/middleware-aborter';
29
20
  import { fatcher } from 'fatcher';
21
+ import { aborter } from '@fatcherjs/middleware-aborter';
30
22
 
31
- fatcher({
32
- url: '/bar/foo',
33
- middlewares: [
34
- aborter({
35
- timeout: 10 * 1000, // 10s
36
- onAbort: () => {
37
- console.log('Request is Aborted.');
38
- },
39
- }),
40
- ],
41
- })
42
- .then(res => {
43
- // Request success in 10s
44
- console.log(res);
45
- })
46
- .catch(err => {
47
- if (isAbortError(err)) {
48
- //Run error when request aborted.
49
- console.error(err);
50
- }
51
-
52
- // Other errors.
53
- });
23
+ fatcher('https://foo.bar', {
24
+ middlewares: [
25
+ aborter({
26
+ /* Options*/
27
+ }),
28
+ ],
29
+ });
54
30
  ```
55
31
 
56
32
  ## Options
57
33
 
58
- | Name | Description | Type | DefaultValue |
59
- | ----------- | ----------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------ |
60
- | timeout | If `timeout > 0`, will abort this request later | `number` | `0` |
61
- | onAbort | A callback when aborting this request | `(() => void) \| null` | `null` |
62
- | concurrency | Request concurrency restrictions | `boolean` | `false` |
63
- | groupBy | Concurrency key | `(context: Readonly<Context>) => string` | `${context.url}_${context.method}_${new URLSearchParams(context.params).toString()}` |
34
+ ### onAbort
35
+
36
+ ```ts
37
+ import { fatcher } from 'fatcher';
38
+ import { aborter } from '@fatcherjs/middleware-aborter';
39
+
40
+ fatcher('https://foo.bar', {
41
+ middlewares: [
42
+ aborter({
43
+ onAbort: () => console.log('aborted'),
44
+ }),
45
+ ],
46
+ });
47
+ ```
48
+
49
+ ### timeout
50
+
51
+ ```ts
52
+ import { fatcher } from 'fatcher';
53
+ import { aborter } from '@fatcherjs/middleware-aborter';
54
+
55
+ fatcher('https://foo.bar', {
56
+ middlewares: [
57
+ aborter({
58
+ timeout: 10 * 1000, // abort in 10 seconds
59
+ }),
60
+ ],
61
+ });
62
+ ```
64
63
 
65
64
  ## License
66
65
 
67
- [MIT](https://github.com/fatcherjs/fatcher/blob/master/LICENSE)
66
+ [MIT](https://github.com/fanhaoyuan/fatcher/blob/master/LICENSE)
@@ -0,0 +1,24 @@
1
+ import { FatcherMiddleware } from 'fatcher';
2
+
3
+ /**
4
+ * Confirm an error whether is DOMException
5
+ * @param error
6
+ * @returns
7
+ */
8
+ declare function isAbortError(error: unknown): error is DOMException;
9
+
10
+ interface AborterOptions {
11
+ timeout?: number;
12
+ signal?: AbortSignal;
13
+ abort?: () => void;
14
+ onAbort?: () => void;
15
+ }
16
+ declare module 'fatcher' {
17
+ interface FatcherRequest {
18
+ abort: () => void;
19
+ }
20
+ }
21
+
22
+ declare const aborter: (options?: AborterOptions) => FatcherMiddleware;
23
+
24
+ export { AborterOptions, aborter, isAbortError };
@@ -0,0 +1,32 @@
1
+ import 'fatcher';
2
+
3
+ function isAbortError(error) {
4
+ return error instanceof DOMException && error.name === "AbortError";
5
+ }
6
+
7
+ const aborter = (options = {}) => {
8
+ return async (req, next) => {
9
+ const { onAbort, timeout } = options;
10
+ const abortController = new AbortController();
11
+ if (onAbort) {
12
+ abortController.signal.addEventListener("abort", () => onAbort());
13
+ }
14
+ const promise = next({
15
+ abort: abortController.abort,
16
+ signal: abortController.signal
17
+ });
18
+ let timer = null;
19
+ if (timeout) {
20
+ timer = setTimeout(() => {
21
+ abortController.abort();
22
+ }, timeout);
23
+ }
24
+ const response = await promise;
25
+ if (timer) {
26
+ clearTimeout(timer);
27
+ }
28
+ return response;
29
+ };
30
+ };
31
+
32
+ export { aborter, isAbortError };
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ require('fatcher');
6
+
7
+ function isAbortError(error) {
8
+ return error instanceof DOMException && error.name === "AbortError";
9
+ }
10
+
11
+ const aborter = (options = {}) => {
12
+ return async (req, next) => {
13
+ const { onAbort, timeout } = options;
14
+ const abortController = new AbortController();
15
+ if (onAbort) {
16
+ abortController.signal.addEventListener("abort", () => onAbort());
17
+ }
18
+ const promise = next({
19
+ abort: abortController.abort,
20
+ signal: abortController.signal
21
+ });
22
+ let timer = null;
23
+ if (timeout) {
24
+ timer = setTimeout(() => {
25
+ abortController.abort();
26
+ }, timeout);
27
+ }
28
+ const response = await promise;
29
+ if (timer) {
30
+ clearTimeout(timer);
31
+ }
32
+ return response;
33
+ };
34
+ };
35
+
36
+ exports.aborter = aborter;
37
+ exports.isAbortError = isAbortError;
@@ -0,0 +1 @@
1
+ (function(e,t){typeof exports=="object"&&typeof module!="undefined"?t(exports):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis!="undefined"?globalThis:e||self,t(e.FatcherMiddlewareAborter={}))})(this,function(e){"use strict";function t(o){return o instanceof DOMException&&o.name==="AbortError"}const a=(o={})=>async(b,u)=>{const{onAbort:i,timeout:s}=o,r=new AbortController;i&&r.signal.addEventListener("abort",()=>i());const f=u({abort:r.abort,signal:r.signal});let n=null;s&&(n=setTimeout(()=>{r.abort()},s));const l=await f;return n&&clearTimeout(n),l};e.aborter=a,e.isAbortError=t,Object.defineProperty(e,"__esModule",{value:!0})});
package/package.json CHANGED
@@ -1,49 +1,27 @@
1
1
  {
2
2
  "name": "@fatcherjs/middleware-aborter",
3
- "version": "2.0.0",
4
- "main": "dist/aborter.js",
5
- "module": "dist/aborter.esm.js",
6
- "browser": "dist/aborter.min.js",
7
- "typings": "dist/aborter.d.ts",
8
- "license": "MIT",
3
+ "homepage": "https://github.com/fanhaoyuan/fatcher",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/fanhaoyuan/fatcher.git"
7
+ },
8
+ "main": "dist/index.js",
9
+ "module": "dist/index.esm.js",
10
+ "browser": "dist/index.min.js",
11
+ "typings": "dist/index.d.ts",
9
12
  "files": [
10
13
  "dist"
11
14
  ],
12
- "homepage": "https://github.com/fatcherjs/fatcher/tree/master/packages/aborter",
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/fatcherjs/fatcher.git"
15
+ "peerDependencies": {
16
+ "fatcher": "3.0.0-alpha-5"
16
17
  },
17
18
  "devDependencies": {
18
- "@fansy/eslint-config": "^1.1.0",
19
- "@fansy/prettier-config": "^1.0.0",
20
- "@jest/types": "^29.1.2",
21
- "@rollup/plugin-node-resolve": "^15.0.0",
22
- "@types/jest": "^29.1.2",
23
- "@types/node": "^18.8.5",
24
- "esbuild": "^0.15.10",
25
- "fatcher": "^2.0.0",
26
- "jest": "^29.1.2",
27
- "jest-fetch-mock": "^3.0.3",
28
- "rimraf": "^3.0.2",
29
- "rollup": "^2.79.1",
30
- "rollup-plugin-dts": "^4.2.3",
31
- "rollup-plugin-esbuild": "^4.10.1",
32
- "ts-jest": "^29.0.3",
33
- "ts-node": "^10.9.1",
34
- "typescript": "^4.8.4"
35
- },
36
- "peerDependencies": {
37
- "fatcher": "^2.0.0"
19
+ "fatcher": "3.0.0-alpha-5"
38
20
  },
21
+ "version": "3.0.0-alpha-5",
39
22
  "scripts": {
40
- "dev": "rimraf dist && rollup -c rollup.config.ts -w",
41
- "build": "rimraf dist && rollup -c rollup.config.ts",
42
- "deploy": "pnpm run build && pnpm publish --no-git-check",
43
- "test": "jest",
44
- "test:cov": "jest --coverage",
45
- "eslint": "eslint .",
46
- "tsc": "tsc --noEmit",
47
- "ci": "npm run eslint && npm run tsc && npm run build && npm run test"
23
+ "clean": "rimraf dist",
24
+ "build": "npm run clean && rollup -c rollup.config.ts",
25
+ "tsc": "tsc --noEmit"
48
26
  }
49
27
  }
package/dist/aborter.d.ts DELETED
@@ -1,59 +0,0 @@
1
- import * as fatcher from 'fatcher';
2
- import { Context } from 'fatcher';
3
-
4
- declare type RoadSign = {
5
- abort: () => void;
6
- signal: AbortSignal;
7
- };
8
- declare type RoadMap = Record<string, RoadSign[]>;
9
- interface AborterMiddlewareContext extends Readonly<Context> {
10
- /**
11
- * Provides with aborter
12
- *
13
- * @require `@fatcherjs/middleware-aborter`
14
- */
15
- abort: () => void;
16
- signal: AbortSignal;
17
- }
18
- interface AborterOptions {
19
- /**
20
- * Request timeout
21
- *
22
- * `ms`
23
- *
24
- * @default 0
25
- */
26
- timeout?: number;
27
- /**
28
- * Callback with aborted request.
29
- *
30
- * @default null
31
- */
32
- onAbort?: (() => void) | null;
33
- /**
34
- * Request concurrency restrictions
35
- *
36
- * @default false
37
- */
38
- concurrency?: boolean;
39
- /**
40
- * Concurrency key.
41
- */
42
- groupBy?: (context: Readonly<Context>) => string;
43
- }
44
-
45
- /**
46
- * A middleware for aborting fatcher request.
47
- * @param options
48
- * @returns
49
- */
50
- declare function aborter(options?: AborterOptions): fatcher.Middleware[];
51
-
52
- /**
53
- * Confirm an error whether is DOMException
54
- * @param error
55
- * @returns
56
- */
57
- declare function isAbortError(error: unknown): error is DOMException;
58
-
59
- export { AborterMiddlewareContext, AborterOptions, RoadMap, RoadSign, aborter, isAbortError };
@@ -1,72 +0,0 @@
1
- import { defineMiddleware } from 'fatcher';
2
-
3
- const roadMap = {};
4
- function aborter(options = {}) {
5
- const { timeout = 0, onAbort = null, concurrency, groupBy } = options;
6
- let _timeout = timeout;
7
- if (isNaN(_timeout) || ~~_timeout < 0) {
8
- console.warn("[fatcher-middleware-aborter] Timeout is not a valid number.");
9
- _timeout = 0;
10
- }
11
- const baseAborter = defineMiddleware(async (context, next) => {
12
- const abortController = new AbortController();
13
- if (onAbort) {
14
- abortController.signal.addEventListener("abort", () => onAbort());
15
- }
16
- return next({
17
- signal: abortController.signal,
18
- abort: abortController.abort.bind(abortController)
19
- });
20
- }, "fatcher-middleware-aborter");
21
- const timeoutAborter = defineMiddleware(async (context, next) => {
22
- const { signal, abort } = context;
23
- let timer = setTimeout(abort, _timeout);
24
- const release = () => {
25
- if (timer) {
26
- clearTimeout(timer);
27
- }
28
- timer = null;
29
- };
30
- signal.addEventListener("abort", release);
31
- const result = await next();
32
- release();
33
- return result;
34
- }, "fatcher-middleware-timeout-aborter");
35
- const concurrencyAborter = defineMiddleware(async (context, next) => {
36
- const { signal, abort } = context;
37
- const group = groupBy ? groupBy(context) : `${context.url}_${context.method}_${new URLSearchParams(context.params)}`;
38
- if (roadMap[group] && roadMap[group].length) {
39
- roadMap[group].forEach((item) => item.abort());
40
- }
41
- if (!roadMap[group]) {
42
- roadMap[group] = [];
43
- }
44
- roadMap[group].push({ abort, signal });
45
- const release = () => {
46
- roadMap[group] = roadMap[group].filter((item) => {
47
- return item.signal !== signal;
48
- });
49
- if (!roadMap[group].length) {
50
- delete roadMap[group];
51
- }
52
- };
53
- signal.addEventListener("abort", release);
54
- const result = await next();
55
- release();
56
- return result;
57
- }, "fatcher-middleware-concurrency-aborter");
58
- const middlewares = [baseAborter];
59
- if (_timeout) {
60
- middlewares.push(timeoutAborter);
61
- }
62
- if (concurrency) {
63
- middlewares.push(concurrencyAborter);
64
- }
65
- return middlewares;
66
- }
67
-
68
- function isAbortError(error) {
69
- return error instanceof DOMException && error.name === "AbortError";
70
- }
71
-
72
- export { aborter, isAbortError };
package/dist/aborter.js DELETED
@@ -1,77 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var fatcher = require('fatcher');
6
-
7
- const roadMap = {};
8
- function aborter(options = {}) {
9
- const { timeout = 0, onAbort = null, concurrency, groupBy } = options;
10
- let _timeout = timeout;
11
- if (isNaN(_timeout) || ~~_timeout < 0) {
12
- console.warn("[fatcher-middleware-aborter] Timeout is not a valid number.");
13
- _timeout = 0;
14
- }
15
- const baseAborter = fatcher.defineMiddleware(async (context, next) => {
16
- const abortController = new AbortController();
17
- if (onAbort) {
18
- abortController.signal.addEventListener("abort", () => onAbort());
19
- }
20
- return next({
21
- signal: abortController.signal,
22
- abort: abortController.abort.bind(abortController)
23
- });
24
- }, "fatcher-middleware-aborter");
25
- const timeoutAborter = fatcher.defineMiddleware(async (context, next) => {
26
- const { signal, abort } = context;
27
- let timer = setTimeout(abort, _timeout);
28
- const release = () => {
29
- if (timer) {
30
- clearTimeout(timer);
31
- }
32
- timer = null;
33
- };
34
- signal.addEventListener("abort", release);
35
- const result = await next();
36
- release();
37
- return result;
38
- }, "fatcher-middleware-timeout-aborter");
39
- const concurrencyAborter = fatcher.defineMiddleware(async (context, next) => {
40
- const { signal, abort } = context;
41
- const group = groupBy ? groupBy(context) : `${context.url}_${context.method}_${new URLSearchParams(context.params)}`;
42
- if (roadMap[group] && roadMap[group].length) {
43
- roadMap[group].forEach((item) => item.abort());
44
- }
45
- if (!roadMap[group]) {
46
- roadMap[group] = [];
47
- }
48
- roadMap[group].push({ abort, signal });
49
- const release = () => {
50
- roadMap[group] = roadMap[group].filter((item) => {
51
- return item.signal !== signal;
52
- });
53
- if (!roadMap[group].length) {
54
- delete roadMap[group];
55
- }
56
- };
57
- signal.addEventListener("abort", release);
58
- const result = await next();
59
- release();
60
- return result;
61
- }, "fatcher-middleware-concurrency-aborter");
62
- const middlewares = [baseAborter];
63
- if (_timeout) {
64
- middlewares.push(timeoutAborter);
65
- }
66
- if (concurrency) {
67
- middlewares.push(concurrencyAborter);
68
- }
69
- return middlewares;
70
- }
71
-
72
- function isAbortError(error) {
73
- return error instanceof DOMException && error.name === "AbortError";
74
- }
75
-
76
- exports.aborter = aborter;
77
- exports.isAbortError = isAbortError;
@@ -1 +0,0 @@
1
- (function(n,i){typeof exports=="object"&&typeof module!="undefined"?i(exports,require("fatcher")):typeof define=="function"&&define.amd?define(["exports","fatcher"],i):(n=typeof globalThis!="undefined"?globalThis:n||self,i(n.FatcherMiddlewareAborter={},n.Fatcher))})(this,function(n,i){"use strict";const r={};function p(c={}){const{timeout:y=0,onAbort:m=null,concurrency:g,groupBy:h}=c;let a=y;(isNaN(a)||~~a<0)&&(console.warn("[fatcher-middleware-aborter] Timeout is not a valid number."),a=0);const A=i.defineMiddleware(async(o,s)=>{const t=new AbortController;return m&&t.signal.addEventListener("abort",()=>m()),s({signal:t.signal,abort:t.abort.bind(t)})},"fatcher-middleware-aborter"),E=i.defineMiddleware(async(o,s)=>{const{signal:t,abort:l}=o;let e=setTimeout(l,a);const d=()=>{e&&clearTimeout(e),e=null};t.addEventListener("abort",d);const f=await s();return d(),f},"fatcher-middleware-timeout-aborter"),M=i.defineMiddleware(async(o,s)=>{const{signal:t,abort:l}=o,e=h?h(o):`${o.url}_${o.method}_${new URLSearchParams(o.params)}`;r[e]&&r[e].length&&r[e].forEach(b=>b.abort()),r[e]||(r[e]=[]),r[e].push({abort:l,signal:t});const d=()=>{r[e]=r[e].filter(b=>b.signal!==t),r[e].length||delete r[e]};t.addEventListener("abort",d);const f=await s();return d(),f},"fatcher-middleware-concurrency-aborter"),u=[A];return a&&u.push(E),g&&u.push(M),u}function w(c){return c instanceof DOMException&&c.name==="AbortError"}n.aborter=p,n.isAbortError=w,Object.defineProperty(n,"__esModule",{value:!0})});