@ahoo-wang/fetcher 0.3.3 → 0.3.6
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/README.md +107 -0
- package/README.zh-CN.md +104 -0
- package/dist/fetcher.d.ts +1 -0
- package/dist/fetcher.d.ts.map +1 -1
- package/dist/fetcherRegistrar.d.ts +4 -0
- package/dist/fetcherRegistrar.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +65 -38
- package/dist/index.umd.js +1 -1
- package/dist/namedFetcher.d.ts +69 -0
- package/dist/namedFetcher.d.ts.map +1 -0
- package/dist/timeout.d.ts.map +1 -1
- package/dist/types.d.ts +3 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -78,6 +78,76 @@ fetcher
|
|
|
78
78
|
});
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
### Named Fetcher Usage
|
|
82
|
+
|
|
83
|
+
NamedFetcher is an extension of the Fetcher class that automatically registers itself with a global registrar. This is
|
|
84
|
+
useful when you need to manage multiple fetcher instances throughout your application.
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { NamedFetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';
|
|
88
|
+
|
|
89
|
+
// Create a named fetcher that automatically registers itself
|
|
90
|
+
const apiFetcher = new NamedFetcher('api', {
|
|
91
|
+
baseURL: 'https://api.example.com',
|
|
92
|
+
timeout: 5000,
|
|
93
|
+
headers: {
|
|
94
|
+
'Content-Type': 'application/json',
|
|
95
|
+
Authorization: 'Bearer token',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Create another named fetcher for a different service
|
|
100
|
+
const authFetcher = new NamedFetcher('auth', {
|
|
101
|
+
baseURL: 'https://auth.example.com',
|
|
102
|
+
timeout: 3000,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Use the fetcher normally
|
|
106
|
+
apiFetcher
|
|
107
|
+
.get('/users/123')
|
|
108
|
+
.then(response => response.json())
|
|
109
|
+
.then(data => console.log(data));
|
|
110
|
+
|
|
111
|
+
// Retrieve a named fetcher from the registrar
|
|
112
|
+
const retrievedFetcher = fetcherRegistrar.get('api');
|
|
113
|
+
if (retrievedFetcher) {
|
|
114
|
+
retrievedFetcher.post('/users', {
|
|
115
|
+
body: { name: 'Jane Doe' },
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Use requiredGet to retrieve a fetcher (throws error if not found)
|
|
120
|
+
try {
|
|
121
|
+
const authFetcher = fetcherRegistrar.requiredGet('auth');
|
|
122
|
+
authFetcher.post('/login', {
|
|
123
|
+
body: { username: 'user', password: 'pass' },
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.error('Fetcher not found:', error.message);
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Default Fetcher Usage
|
|
131
|
+
|
|
132
|
+
The library also exports a pre-configured default fetcher instance that can be used directly:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import { fetcher } from '@ahoo-wang/fetcher';
|
|
136
|
+
|
|
137
|
+
// Use the default fetcher directly
|
|
138
|
+
fetcher
|
|
139
|
+
.get('/users')
|
|
140
|
+
.then(response => response.json())
|
|
141
|
+
.then(data => console.log(data));
|
|
142
|
+
|
|
143
|
+
// The default fetcher is also available through the registrar
|
|
144
|
+
import { fetcherRegistrar } from '@ahoo-wang/fetcher';
|
|
145
|
+
|
|
146
|
+
const defaultFetcher = fetcherRegistrar.default;
|
|
147
|
+
// defaultFetcher is the same instance as fetcher
|
|
148
|
+
console.log(defaultFetcher === fetcher); // true
|
|
149
|
+
```
|
|
150
|
+
|
|
81
151
|
### Interceptor Usage
|
|
82
152
|
|
|
83
153
|
```typescript
|
|
@@ -149,6 +219,43 @@ new Fetcher(options: FetcherOptions = defaultOptions)
|
|
|
149
219
|
- `head(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - HEAD request
|
|
150
220
|
- `options(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - OPTIONS request
|
|
151
221
|
|
|
222
|
+
### NamedFetcher Class
|
|
223
|
+
|
|
224
|
+
An extension of the Fetcher class that automatically registers itself with the global fetcherRegistrar using a provided
|
|
225
|
+
name.
|
|
226
|
+
|
|
227
|
+
#### Constructor
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
new NamedFetcher(name
|
|
231
|
+
:
|
|
232
|
+
string, options
|
|
233
|
+
:
|
|
234
|
+
FetcherOptions = defaultOptions
|
|
235
|
+
)
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
**Parameters:**
|
|
239
|
+
|
|
240
|
+
- `name`: The name to register this fetcher under
|
|
241
|
+
- `options`: Same as Fetcher constructor options
|
|
242
|
+
|
|
243
|
+
### FetcherRegistrar
|
|
244
|
+
|
|
245
|
+
Global instance for managing multiple Fetcher instances by name.
|
|
246
|
+
|
|
247
|
+
#### Properties
|
|
248
|
+
|
|
249
|
+
- `default`: Get or set the default fetcher instance
|
|
250
|
+
|
|
251
|
+
#### Methods
|
|
252
|
+
|
|
253
|
+
- `register(name: string, fetcher: Fetcher): void` - Register a fetcher with a name
|
|
254
|
+
- `unregister(name: string): boolean` - Unregister a fetcher by name
|
|
255
|
+
- `get(name: string): Fetcher | undefined` - Get a fetcher by name
|
|
256
|
+
- `requiredGet(name: string): Fetcher` - Get a fetcher by name, throws if not found
|
|
257
|
+
- `fetchers: Map<string, Fetcher>` - Get all registered fetchers
|
|
258
|
+
|
|
152
259
|
### UrlBuilder Class
|
|
153
260
|
|
|
154
261
|
URL builder for constructing complete URLs with parameters.
|
package/README.zh-CN.md
CHANGED
|
@@ -78,6 +78,76 @@ fetcher
|
|
|
78
78
|
});
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
### 命名 Fetcher 用法
|
|
82
|
+
|
|
83
|
+
NamedFetcher 是 Fetcher 类的扩展,它会自动使用提供的名称在全局注册器中注册自己。当您需要在应用程序中管理多个 fetcher
|
|
84
|
+
实例时,这很有用。
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { NamedFetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';
|
|
88
|
+
|
|
89
|
+
// 创建一个自动注册自己的命名 fetcher
|
|
90
|
+
const apiFetcher = new NamedFetcher('api', {
|
|
91
|
+
baseURL: 'https://api.example.com',
|
|
92
|
+
timeout: 5000,
|
|
93
|
+
headers: {
|
|
94
|
+
'Content-Type': 'application/json',
|
|
95
|
+
Authorization: 'Bearer token',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// 为不同的服务创建另一个命名 fetcher
|
|
100
|
+
const authFetcher = new NamedFetcher('auth', {
|
|
101
|
+
baseURL: 'https://auth.example.com',
|
|
102
|
+
timeout: 3000,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// 正常使用 fetcher
|
|
106
|
+
apiFetcher
|
|
107
|
+
.get('/users/123')
|
|
108
|
+
.then(response => response.json())
|
|
109
|
+
.then(data => console.log(data));
|
|
110
|
+
|
|
111
|
+
// 从注册器中检索命名 fetcher
|
|
112
|
+
const retrievedFetcher = fetcherRegistrar.get('api');
|
|
113
|
+
if (retrievedFetcher) {
|
|
114
|
+
retrievedFetcher.post('/users', {
|
|
115
|
+
body: { name: 'Jane Doe' },
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 使用 requiredGet 检索 fetcher(如果未找到则抛出错误)
|
|
120
|
+
try {
|
|
121
|
+
const authFetcher = fetcherRegistrar.requiredGet('auth');
|
|
122
|
+
authFetcher.post('/login', {
|
|
123
|
+
body: { username: 'user', password: 'pass' },
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.error('未找到 Fetcher:', error.message);
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### 默认 Fetcher 用法
|
|
131
|
+
|
|
132
|
+
该库还导出了一个预配置的默认 fetcher 实例,可以直接使用:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import { fetcher } from '@ahoo-wang/fetcher';
|
|
136
|
+
|
|
137
|
+
// 直接使用默认 fetcher
|
|
138
|
+
fetcher
|
|
139
|
+
.get('/users')
|
|
140
|
+
.then(response => response.json())
|
|
141
|
+
.then(data => console.log(data));
|
|
142
|
+
|
|
143
|
+
// 默认 fetcher 也可以通过注册器获取
|
|
144
|
+
import { fetcherRegistrar } from '@ahoo-wang/fetcher';
|
|
145
|
+
|
|
146
|
+
const defaultFetcher = fetcherRegistrar.default;
|
|
147
|
+
// defaultFetcher 与 fetcher 是同一个实例
|
|
148
|
+
console.log(defaultFetcher === fetcher); // true
|
|
149
|
+
```
|
|
150
|
+
|
|
81
151
|
### 拦截器用法
|
|
82
152
|
|
|
83
153
|
```typescript
|
|
@@ -149,6 +219,40 @@ new Fetcher(options?: FetcherOptions)
|
|
|
149
219
|
- `head(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - HEAD 请求
|
|
150
220
|
- `options(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - OPTIONS 请求
|
|
151
221
|
|
|
222
|
+
### NamedFetcher 类
|
|
223
|
+
|
|
224
|
+
Fetcher 类的扩展,它会自动使用提供的名称在全局 fetcherRegistrar 中注册自己。
|
|
225
|
+
|
|
226
|
+
#### 构造函数
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
new NamedFetcher(name
|
|
230
|
+
:
|
|
231
|
+
string, options ? : FetcherOptions
|
|
232
|
+
)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
**参数:**
|
|
236
|
+
|
|
237
|
+
- `name`:注册此 fetcher 的名称
|
|
238
|
+
- `options`:与 Fetcher 构造函数相同的选项
|
|
239
|
+
|
|
240
|
+
### FetcherRegistrar
|
|
241
|
+
|
|
242
|
+
用于按名称管理多个 Fetcher 实例的全局实例。
|
|
243
|
+
|
|
244
|
+
#### 属性
|
|
245
|
+
|
|
246
|
+
- `default`:获取或设置默认 fetcher 实例
|
|
247
|
+
|
|
248
|
+
#### 方法
|
|
249
|
+
|
|
250
|
+
- `register(name: string, fetcher: Fetcher): void` - 使用名称注册 fetcher
|
|
251
|
+
- `unregister(name: string): boolean` - 按名称注销 fetcher
|
|
252
|
+
- `get(name: string): Fetcher | undefined` - 按名称获取 fetcher
|
|
253
|
+
- `requiredGet(name: string): Fetcher` - 按名称获取 fetcher,如果未找到则抛出错误
|
|
254
|
+
- `fetchers: Map<string, Fetcher>` - 获取所有已注册的 fetcher
|
|
255
|
+
|
|
152
256
|
### UrlBuilder 类
|
|
153
257
|
|
|
154
258
|
用于构建带参数的完整 URL 的 URL 构建器。
|
package/dist/fetcher.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { FetcherInterceptors, FetchExchange } from './interceptor';
|
|
|
6
6
|
*/
|
|
7
7
|
export interface FetcherOptions extends BaseURLCapable, HeadersCapable, TimeoutCapable {
|
|
8
8
|
}
|
|
9
|
+
export declare const defaultOptions: FetcherOptions;
|
|
9
10
|
/**
|
|
10
11
|
* Fetcher request options interface
|
|
11
12
|
*/
|
package/dist/fetcher.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher.d.ts","sourceRoot":"","sources":["../src/fetcher.ts"],"names":[],"mappings":"AAcA,OAAO,EAAqC,cAAc,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EACL,cAAc,EAGd,cAAc,EAEd,YAAY,EACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGnE;;GAEG;AACH,MAAM,WAAW,cACf,SAAQ,cAAc,EACpB,cAAc,EACd,cAAc;CACjB;
|
|
1
|
+
{"version":3,"file":"fetcher.d.ts","sourceRoot":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|
4
|
+
*/
|
|
5
|
+
export declare const defaultFetcherName = "default";
|
|
2
6
|
/**
|
|
3
7
|
* FetcherRegistrar is a registry for managing multiple Fetcher instances.
|
|
4
8
|
* It allows registering, retrieving, and unregistering Fetcher instances by name.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcherRegistrar.d.ts","sourceRoot":"","sources":["../src/fetcherRegistrar.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"fetcherRegistrar.d.ts","sourceRoot":"","sources":["../src/fetcherRegistrar.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;GAEG;AACH,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,gBAAgB;IAC3B;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAmC;IAEpD;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAI9C;;;;;;;;;;OAUG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIjC;;;;;;;;;;OAUG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAItC;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAQlC;;;;;;;OAOG;IACH,IAAI,OAAO,IAAI,OAAO,CAErB;IAED;;;;;;;OAOG;IACH,IAAI,OAAO,CAAC,OAAO,EAAE,OAAO,EAE3B;IAED;;;;;;;;;OASG;IACH,IAAI,QAAQ,IAAI,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAEnC;CACF;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,kBAAyB,CAAC"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
function
|
|
1
|
+
function b(r) {
|
|
2
2
|
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(r);
|
|
3
3
|
}
|
|
4
|
-
function
|
|
5
|
-
return
|
|
4
|
+
function g(r, e) {
|
|
5
|
+
return b(e) ? e : e ? r.replace(/\/?\/$/, "") + "/" + e.replace(/^\/+/, "") : r;
|
|
6
6
|
}
|
|
7
|
-
class
|
|
7
|
+
class P {
|
|
8
8
|
/**
|
|
9
9
|
* 创建UrlBuilder实例
|
|
10
10
|
*
|
|
@@ -23,7 +23,7 @@ class g {
|
|
|
23
23
|
* @throws 当路径参数中缺少必需的占位符时抛出错误
|
|
24
24
|
*/
|
|
25
25
|
build(e, t, s) {
|
|
26
|
-
let i =
|
|
26
|
+
let i = g(this.baseURL, e), o = this.interpolateUrl(i, t);
|
|
27
27
|
if (s) {
|
|
28
28
|
const n = new URLSearchParams(s).toString();
|
|
29
29
|
n && (o += "?" + n);
|
|
@@ -47,18 +47,18 @@ class g {
|
|
|
47
47
|
}) : e;
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
-
function
|
|
50
|
+
function O(r, e) {
|
|
51
51
|
return typeof r < "u" ? r : e;
|
|
52
52
|
}
|
|
53
|
-
class
|
|
53
|
+
class f extends Error {
|
|
54
54
|
constructor(e, t) {
|
|
55
55
|
const s = e.request?.method || "GET", i = `Request timeout of ${t}ms exceeded for ${s} ${e.url}`;
|
|
56
|
-
super(i), this.name = "FetchTimeoutError", this.exchange = e, Object.setPrototypeOf(this,
|
|
56
|
+
super(i), this.name = "FetchTimeoutError", this.exchange = e, Object.setPrototypeOf(this, f.prototype);
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
-
var c = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r))(c || {}),
|
|
59
|
+
var c = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r))(c || {}), q = /* @__PURE__ */ ((r) => (r.METHOD = "method", r.BODY = "body", r))(q || {});
|
|
60
60
|
const d = "Content-Type";
|
|
61
|
-
var
|
|
61
|
+
var p = /* @__PURE__ */ ((r) => (r.APPLICATION_JSON = "application/json", r.TEXT_EVENT_STREAM = "text/event-stream", r))(p || {});
|
|
62
62
|
class h {
|
|
63
63
|
constructor() {
|
|
64
64
|
this.interceptors = [];
|
|
@@ -97,7 +97,7 @@ class h {
|
|
|
97
97
|
return t;
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
-
class
|
|
100
|
+
class F {
|
|
101
101
|
constructor() {
|
|
102
102
|
this.request = new h(), this.response = new h(), this.error = new h();
|
|
103
103
|
}
|
|
@@ -133,23 +133,23 @@ class A {
|
|
|
133
133
|
const s = { ...t };
|
|
134
134
|
s.body = JSON.stringify(t.body), s.headers || (s.headers = {});
|
|
135
135
|
const i = s.headers;
|
|
136
|
-
return i[d] || (i[d] =
|
|
136
|
+
return i[d] || (i[d] = p.APPLICATION_JSON), { ...e, request: s };
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
139
|
const y = {
|
|
140
|
-
[d]:
|
|
141
|
-
},
|
|
140
|
+
[d]: p.APPLICATION_JSON
|
|
141
|
+
}, T = {
|
|
142
142
|
baseURL: "",
|
|
143
143
|
headers: y
|
|
144
144
|
};
|
|
145
|
-
class
|
|
145
|
+
class S {
|
|
146
146
|
/**
|
|
147
147
|
* Create a Fetcher instance
|
|
148
148
|
*
|
|
149
149
|
* @param options - Fetcher configuration options
|
|
150
150
|
*/
|
|
151
|
-
constructor(e =
|
|
152
|
-
this.headers = y, this.interceptors = new
|
|
151
|
+
constructor(e = T) {
|
|
152
|
+
this.headers = y, this.interceptors = new F(), this.urlBuilder = new P(e.baseURL), e.headers !== void 0 && (this.headers = e.headers), this.timeout = e.timeout, this.interceptors.request.use(new A());
|
|
153
153
|
}
|
|
154
154
|
/**
|
|
155
155
|
* Make an HTTP request
|
|
@@ -219,7 +219,7 @@ class I {
|
|
|
219
219
|
* @throws FetchTimeoutError Thrown when the request times out
|
|
220
220
|
*/
|
|
221
221
|
async timeoutFetch(e) {
|
|
222
|
-
const t = e.url, s = e.request, i = s.timeout, o =
|
|
222
|
+
const t = e.url, s = e.request, i = s.timeout, o = O(i, this.timeout);
|
|
223
223
|
if (!o)
|
|
224
224
|
return fetch(t, s);
|
|
225
225
|
const n = new AbortController(), u = {
|
|
@@ -227,17 +227,17 @@ class I {
|
|
|
227
227
|
signal: n.signal
|
|
228
228
|
};
|
|
229
229
|
let a = null;
|
|
230
|
-
const
|
|
230
|
+
const w = new Promise((U, E) => {
|
|
231
231
|
a = setTimeout(() => {
|
|
232
232
|
a && clearTimeout(a);
|
|
233
|
-
const
|
|
234
|
-
n.abort(
|
|
233
|
+
const m = new f(e, o);
|
|
234
|
+
n.abort(m), E(m);
|
|
235
235
|
}, o);
|
|
236
236
|
});
|
|
237
237
|
try {
|
|
238
238
|
return await Promise.race([
|
|
239
239
|
fetch(t, u),
|
|
240
|
-
|
|
240
|
+
w
|
|
241
241
|
]);
|
|
242
242
|
} finally {
|
|
243
243
|
a && clearTimeout(a);
|
|
@@ -328,8 +328,8 @@ class I {
|
|
|
328
328
|
return this.methodFetch(c.OPTIONS, e, t);
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
|
-
const
|
|
332
|
-
class
|
|
331
|
+
const l = "default";
|
|
332
|
+
class R {
|
|
333
333
|
constructor() {
|
|
334
334
|
this.registrar = /* @__PURE__ */ new Map();
|
|
335
335
|
}
|
|
@@ -402,7 +402,7 @@ class S {
|
|
|
402
402
|
* const defaultFetcher = fetcherRegistrar.default;
|
|
403
403
|
*/
|
|
404
404
|
get default() {
|
|
405
|
-
return this.requiredGet(
|
|
405
|
+
return this.requiredGet(l);
|
|
406
406
|
}
|
|
407
407
|
/**
|
|
408
408
|
* Set the default Fetcher instance
|
|
@@ -413,7 +413,7 @@ class S {
|
|
|
413
413
|
* fetcherRegistrar.default = fetcher;
|
|
414
414
|
*/
|
|
415
415
|
set default(e) {
|
|
416
|
-
this.register(
|
|
416
|
+
this.register(l, e);
|
|
417
417
|
}
|
|
418
418
|
/**
|
|
419
419
|
* Get a copy of all registered fetchers
|
|
@@ -429,20 +429,47 @@ class S {
|
|
|
429
429
|
return new Map(this.registrar);
|
|
430
430
|
}
|
|
431
431
|
}
|
|
432
|
-
const
|
|
432
|
+
const I = new R();
|
|
433
|
+
class N extends S {
|
|
434
|
+
/**
|
|
435
|
+
* Create a NamedFetcher instance and automatically register it with the global fetcherRegistrar
|
|
436
|
+
*
|
|
437
|
+
* @param name - The name to register this fetcher under
|
|
438
|
+
* @param options - Fetcher configuration options (same as Fetcher constructor)
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* // Create with default options
|
|
442
|
+
* const fetcher1 = new NamedFetcher('default');
|
|
443
|
+
*
|
|
444
|
+
* // Create with custom options
|
|
445
|
+
* const fetcher2 = new NamedFetcher('api', {
|
|
446
|
+
* baseURL: 'https://api.example.com',
|
|
447
|
+
* timeout: 5000,
|
|
448
|
+
* headers: { 'Authorization': 'Bearer token' }
|
|
449
|
+
* });
|
|
450
|
+
*/
|
|
451
|
+
constructor(e, t = T) {
|
|
452
|
+
super(t), this.name = e, I.register(e, this);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const L = new N(l);
|
|
433
456
|
export {
|
|
434
457
|
d as ContentTypeHeader,
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
458
|
+
p as ContentTypeValues,
|
|
459
|
+
f as FetchTimeoutError,
|
|
460
|
+
S as Fetcher,
|
|
461
|
+
F as FetcherInterceptors,
|
|
462
|
+
R as FetcherRegistrar,
|
|
440
463
|
c as HttpMethod,
|
|
441
464
|
h as InterceptorManager,
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
465
|
+
N as NamedFetcher,
|
|
466
|
+
q as RequestField,
|
|
467
|
+
P as UrlBuilder,
|
|
468
|
+
g as combineURLs,
|
|
469
|
+
l as defaultFetcherName,
|
|
470
|
+
T as defaultOptions,
|
|
471
|
+
L as fetcher,
|
|
472
|
+
I as fetcherRegistrar,
|
|
473
|
+
b as isAbsoluteURL,
|
|
474
|
+
O as resolveTimeout
|
|
448
475
|
};
|
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(n,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(n=typeof globalThis<"u"?globalThis:n||self,h(n.Fetcher={}))})(this,(function(n){"use strict";function h(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function
|
|
1
|
+
(function(n,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(n=typeof globalThis<"u"?globalThis:n||self,h(n.Fetcher={}))})(this,(function(n){"use strict";function h(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function b(r,e){return h(e)?e:e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}class g{constructor(e){this.baseURL=e}build(e,t,s){let o=b(this.baseURL,e),c=this.interpolateUrl(o,t);if(s){const i=new URLSearchParams(s).toString();i&&(c+="?"+i)}return c}interpolateUrl(e,t){return t?e.replace(/{([^}]+)}/g,(s,o)=>{const c=t[o];if(c===void 0)throw new Error(`Missing required path parameter: ${o}`);return String(c)}):e}}function w(r,e){return typeof r<"u"?r:e}class f extends Error{constructor(e,t){const s=e.request?.method||"GET",o=`Request timeout of ${t}ms exceeded for ${s} ${e.url}`;super(o),this.name="FetchTimeoutError",this.exchange=e,Object.setPrototypeOf(this,f.prototype)}}var u=(r=>(r.GET="GET",r.POST="POST",r.PUT="PUT",r.DELETE="DELETE",r.PATCH="PATCH",r.HEAD="HEAD",r.OPTIONS="OPTIONS",r))(u||{}),E=(r=>(r.METHOD="method",r.BODY="body",r))(E||{});const l="Content-Type";var m=(r=>(r.APPLICATION_JSON="application/json",r.TEXT_EVENT_STREAM="text/event-stream",r))(m||{});class p{constructor(){this.interceptors=[]}use(e){const t=this.interceptors.length;return this.interceptors.push(e),t}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}async intercept(e){let t=e;for(let s of this.interceptors)s&&(t=await s.intercept(t));return t}}class F{constructor(){this.request=new p,this.response=new p,this.error=new p}}class U{intercept(e){const t=e.request;if(t.body===void 0||t.body===null||typeof t.body!="object"||t.body instanceof ArrayBuffer||ArrayBuffer.isView(t.body)||t.body instanceof Blob||t.body instanceof File||t.body instanceof URLSearchParams||t.body instanceof FormData||t.body instanceof ReadableStream)return e;const s={...t};s.body=JSON.stringify(t.body),s.headers||(s.headers={});const o=s.headers;return o[l]||(o[l]=m.APPLICATION_JSON),{...e,request:s}}}const P={[l]:m.APPLICATION_JSON},T={baseURL:"",headers:P};class O{constructor(e=T){this.headers=P,this.interceptors=new F,this.urlBuilder=new g(e.baseURL),e.headers!==void 0&&(this.headers=e.headers),this.timeout=e.timeout,this.interceptors.request.use(new U)}async fetch(e,t={}){const s=await this.request(e,t);if(!s.response)throw new Error(`Request to ${s.url} failed with no response`);return s.response}async request(e,t={}){const s={...this.headers||{},...t.headers||{}},o={...t,headers:Object.keys(s).length>0?s:void 0},c=this.urlBuilder.build(e,t.pathParams,t.queryParams);let i={fetcher:this,url:c,request:o,response:void 0,error:void 0};try{const d={...i};i=await this.interceptors.request.intercept(d),i.response=await this.timeoutFetch(i);const a={...i};return i=await this.interceptors.response.intercept(a),i}catch(d){if(i.error=d,i=await this.interceptors.error.intercept(i),i.response)return i;throw i.error}}async timeoutFetch(e){const t=e.url,s=e.request,o=s.timeout,c=w(o,this.timeout);if(!c)return fetch(t,s);const i=new AbortController,d={...s,signal:i.signal};let a=null;const N=new Promise((v,L)=>{a=setTimeout(()=>{a&&clearTimeout(a);const A=new f(e,c);i.abort(A),L(A)},c)});try{return await Promise.race([fetch(t,d),N])}finally{a&&clearTimeout(a)}}async methodFetch(e,t,s={}){return this.fetch(t,{...s,method:e})}async get(e,t={}){return this.methodFetch(u.GET,e,t)}async post(e,t={}){return this.methodFetch(u.POST,e,t)}async put(e,t={}){return this.methodFetch(u.PUT,e,t)}async delete(e,t={}){return this.methodFetch(u.DELETE,e,t)}async patch(e,t={}){return this.methodFetch(u.PATCH,e,t)}async head(e,t={}){return this.methodFetch(u.HEAD,e,t)}async options(e,t={}){return this.methodFetch(u.OPTIONS,e,t)}}const y="default";class q{constructor(){this.registrar=new Map}register(e,t){this.registrar.set(e,t)}unregister(e){return this.registrar.delete(e)}get(e){return this.registrar.get(e)}requiredGet(e){const t=this.get(e);if(!t)throw new Error(`Fetcher ${e} not found`);return t}get default(){return this.requiredGet(y)}set default(e){this.register(y,e)}get fetchers(){return new Map(this.registrar)}}const R=new q;class S extends O{constructor(e,t=T){super(t),this.name=e,R.register(e,this)}}const I=new S(y);n.ContentTypeHeader=l,n.ContentTypeValues=m,n.FetchTimeoutError=f,n.Fetcher=O,n.FetcherInterceptors=F,n.FetcherRegistrar=q,n.HttpMethod=u,n.InterceptorManager=p,n.NamedFetcher=S,n.RequestField=E,n.UrlBuilder=g,n.combineURLs=b,n.defaultFetcherName=y,n.defaultOptions=T,n.fetcher=I,n.fetcherRegistrar=R,n.isAbsoluteURL=h,n.resolveTimeout=w,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { NamedCapable } from './types';
|
|
2
|
+
import { Fetcher, FetcherOptions } from './fetcher';
|
|
3
|
+
/**
|
|
4
|
+
* NamedFetcher is an extension of the Fetcher class that automatically registers
|
|
5
|
+
* itself with the global fetcherRegistrar using a provided name.
|
|
6
|
+
* This allows for easy management and retrieval of multiple fetcher instances
|
|
7
|
+
* throughout an application by name.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* // Create a named fetcher that automatically registers itself
|
|
11
|
+
* const apiFetcher = new NamedFetcher('api', {
|
|
12
|
+
* baseURL: 'https://api.example.com',
|
|
13
|
+
* timeout: 5000
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* // Retrieve the fetcher later by name
|
|
17
|
+
* const sameFetcher = fetcherRegistrar.get('api');
|
|
18
|
+
* console.log(apiFetcher === sameFetcher); // true
|
|
19
|
+
*
|
|
20
|
+
* // Use the fetcher normally
|
|
21
|
+
* const response = await apiFetcher.get('/users');
|
|
22
|
+
*/
|
|
23
|
+
export declare class NamedFetcher extends Fetcher implements NamedCapable {
|
|
24
|
+
/**
|
|
25
|
+
* The name of this fetcher instance, used for registration and retrieval
|
|
26
|
+
*/
|
|
27
|
+
name: string;
|
|
28
|
+
/**
|
|
29
|
+
* Create a NamedFetcher instance and automatically register it with the global fetcherRegistrar
|
|
30
|
+
*
|
|
31
|
+
* @param name - The name to register this fetcher under
|
|
32
|
+
* @param options - Fetcher configuration options (same as Fetcher constructor)
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* // Create with default options
|
|
36
|
+
* const fetcher1 = new NamedFetcher('default');
|
|
37
|
+
*
|
|
38
|
+
* // Create with custom options
|
|
39
|
+
* const fetcher2 = new NamedFetcher('api', {
|
|
40
|
+
* baseURL: 'https://api.example.com',
|
|
41
|
+
* timeout: 5000,
|
|
42
|
+
* headers: { 'Authorization': 'Bearer token' }
|
|
43
|
+
* });
|
|
44
|
+
*/
|
|
45
|
+
constructor(name: string, options?: FetcherOptions);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Default named fetcher instance registered with the name 'default'.
|
|
49
|
+
* This provides a convenient way to use a pre-configured fetcher instance
|
|
50
|
+
* without having to create and register one manually.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* // Use the default fetcher directly
|
|
54
|
+
* import { fetcher } from '@ahoo-wang/fetcher';
|
|
55
|
+
*
|
|
56
|
+
* fetcher.get('/users')
|
|
57
|
+
* .then(response => response.json())
|
|
58
|
+
* .then(data => console.log(data));
|
|
59
|
+
*
|
|
60
|
+
* // Or retrieve it from the registrar
|
|
61
|
+
* import { fetcherRegistrar } from '@ahoo-wang/fetcher';
|
|
62
|
+
*
|
|
63
|
+
* const defaultFetcher = fetcherRegistrar.default;
|
|
64
|
+
* defaultFetcher.get('/users')
|
|
65
|
+
* .then(response => response.json())
|
|
66
|
+
* .then(data => console.log(data));
|
|
67
|
+
*/
|
|
68
|
+
export declare const fetcher: NamedFetcher;
|
|
69
|
+
//# sourceMappingURL=namedFetcher.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"namedFetcher.d.ts","sourceRoot":"","sources":["../src/namedFetcher.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAkB,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGpE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,YAAa,SAAQ,OAAQ,YAAW,YAAY;IAC/D;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;;;;;;;;;;;;;OAgBG;gBACS,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,cAA+B;CAKnE;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,OAAO,cAAuC,CAAC"}
|
package/dist/timeout.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,EAAE,aAAa,CAAC;gBAEZ,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM;CAUrD"}
|
package/dist/types.d.ts
CHANGED
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD,oBAAY,iBAAiB;IAC3B,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;CACxC"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD,oBAAY,iBAAiB;IAC3B,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;CACxC;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd"}
|