@ahoo-wang/fetcher 0.5.0 → 0.5.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/README.md CHANGED
@@ -50,8 +50,8 @@ const fetcher = new Fetcher({
50
50
 
51
51
  // GET request with path and query parameters
52
52
  const response = await fetcher.get('/users/{id}', {
53
- pathParams: { id: 123 },
54
- queryParams: { include: 'profile' },
53
+ path: { id: 123 },
54
+ query: { include: 'profile' },
55
55
  });
56
56
  const userData = await response.json();
57
57
 
package/README.zh-CN.md CHANGED
@@ -49,8 +49,8 @@ const fetcher = new Fetcher({
49
49
 
50
50
  // 带路径和查询参数的 GET 请求
51
51
  const response = await fetcher.get('/users/{id}', {
52
- pathParams: { id: 123 },
53
- queryParams: { include: 'profile' },
52
+ path: { id: 123 },
53
+ query: { include: 'profile' },
54
54
  });
55
55
  const userData = await response.json();
56
56
 
package/dist/fetcher.d.ts CHANGED
@@ -8,11 +8,86 @@ export interface FetcherOptions extends BaseURLCapable, HeadersCapable, TimeoutC
8
8
  }
9
9
  export declare const defaultOptions: FetcherOptions;
10
10
  /**
11
- * Fetcher request options interface
11
+ * Fetcher request configuration interface
12
+ *
13
+ * This interface defines all the configuration options available for making HTTP requests
14
+ * with the Fetcher client. It extends the standard RequestInit interface while adding
15
+ * Fetcher-specific features like path parameters, query parameters, and timeout control.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const request: FetcherRequest = {
20
+ * method: 'GET',
21
+ * path: { id: 123 },
22
+ * query: { include: 'profile' },
23
+ * headers: { 'Authorization': 'Bearer token' },
24
+ * timeout: 5000
25
+ * };
26
+ *
27
+ * const response = await fetcher.fetch('/users/{id}', request);
28
+ * ```
12
29
  */
13
30
  export interface FetcherRequest extends TimeoutCapable, Omit<RequestInit, 'body'> {
14
- pathParams?: Record<string, any>;
15
- queryParams?: Record<string, any>;
31
+ /**
32
+ * Path parameters for URL templating
33
+ *
34
+ * An object containing key-value pairs that will be used to replace placeholders
35
+ * in the URL path. Placeholders are specified using curly braces, e.g., '/users/{id}'.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * // With URL '/users/{id}/posts/{postId}'
40
+ * const request = {
41
+ * path: { id: 123, postId: 456 }
42
+ * };
43
+ * // Results in URL: '/users/123/posts/456'
44
+ * ```
45
+ */
46
+ path?: Record<string, any>;
47
+ /**
48
+ * Query parameters for URL query string
49
+ *
50
+ * An object containing key-value pairs that will be serialized and appended
51
+ * to the URL as query parameters. Arrays are serialized as multiple parameters
52
+ * with the same name, and objects are JSON-stringified.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const request = {
57
+ * query: {
58
+ * limit: 10,
59
+ * filter: 'active',
60
+ * tags: ['important', 'urgent']
61
+ * }
62
+ * };
63
+ * // Results in query string: '?limit=10&filter=active&tags=important&tags=urgent'
64
+ * ```
65
+ */
66
+ query?: Record<string, any>;
67
+ /**
68
+ * Request body
69
+ *
70
+ * The body of the request. Can be a string, Blob, ArrayBuffer, FormData,
71
+ * URLSearchParams, or a plain object. Plain objects are automatically
72
+ * converted to JSON and the appropriate Content-Type header is set.
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * // Plain object (automatically converted to JSON)
77
+ * const request = {
78
+ * method: 'POST',
79
+ * body: { name: 'John', email: 'john@example.com' }
80
+ * };
81
+ *
82
+ * // FormData
83
+ * const formData = new FormData();
84
+ * formData.append('name', 'John');
85
+ * const request = {
86
+ * method: 'POST',
87
+ * body: formData
88
+ * };
89
+ * ```
90
+ */
16
91
  body?: BodyInit | Record<string, any> | null;
17
92
  }
18
93
  /**
@@ -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,E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,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,IAAI,CACR,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,GAAG,CACP,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,MAAM,CACV,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,KAAK,CACT,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,IAAI,CACR,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;CAGrB"}
package/dist/index.es.js CHANGED
@@ -17,8 +17,8 @@ class P {
17
17
  * 构建完整的URL,包括路径参数替换和查询参数添加
18
18
  *
19
19
  * @param url - 需要构建的URL路径
20
- * @param pathParams - 路径参数对象,用于替换URL中的占位符(如{id})
21
- * @param queryParams - 查询参数对象,将被添加到URL查询字符串中
20
+ * @param path - 路径参数对象,用于替换URL中的占位符(如{id})
21
+ * @param query - 查询参数对象,将被添加到URL查询字符串中
22
22
  * @returns 完整的URL字符串
23
23
  * @throws 当路径参数中缺少必需的占位符时抛出错误
24
24
  */
@@ -34,7 +34,7 @@ class P {
34
34
  * 替换url中的占位符参数
35
35
  *
36
36
  * @param url - 包含占位符的路径字符串,如 "http://localhost/users/{id}/posts/{postId}"
37
- * @param pathParams - 路径参数对象,用于替换路径中的占位符
37
+ * @param path - 路径参数对象,用于替换路径中的占位符
38
38
  * @returns 替换占位符后的路径字符串
39
39
  * @throws 当路径参数中缺少必需的占位符时抛出错误
40
40
  */
@@ -180,11 +180,7 @@ class S {
180
180
  }, i = {
181
181
  ...t,
182
182
  headers: Object.keys(s).length > 0 ? s : void 0
183
- }, o = this.urlBuilder.build(
184
- e,
185
- t.pathParams,
186
- t.queryParams
187
- );
183
+ }, o = this.urlBuilder.build(e, t.path, t.query);
188
184
  let n = {
189
185
  fetcher: this,
190
186
  url: o,
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 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"})}));
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.path,t.query);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"})}));
@@ -19,20 +19,20 @@ export declare class UrlBuilder implements BaseURLCapable {
19
19
  * 构建完整的URL,包括路径参数替换和查询参数添加
20
20
  *
21
21
  * @param url - 需要构建的URL路径
22
- * @param pathParams - 路径参数对象,用于替换URL中的占位符(如{id})
23
- * @param queryParams - 查询参数对象,将被添加到URL查询字符串中
22
+ * @param path - 路径参数对象,用于替换URL中的占位符(如{id})
23
+ * @param query - 查询参数对象,将被添加到URL查询字符串中
24
24
  * @returns 完整的URL字符串
25
25
  * @throws 当路径参数中缺少必需的占位符时抛出错误
26
26
  */
27
- build(url: string, pathParams?: Record<string, any>, queryParams?: Record<string, any>): string;
27
+ build(url: string, path?: Record<string, any>, query?: Record<string, any>): string;
28
28
  /**
29
29
  * 替换url中的占位符参数
30
30
  *
31
31
  * @param url - 包含占位符的路径字符串,如 "http://localhost/users/{id}/posts/{postId}"
32
- * @param pathParams - 路径参数对象,用于替换路径中的占位符
32
+ * @param path - 路径参数对象,用于替换路径中的占位符
33
33
  * @returns 替换占位符后的路径字符串
34
34
  * @throws 当路径参数中缺少必需的占位符时抛出错误
35
35
  */
36
- interpolateUrl(url: string, pathParams?: Record<string, any>): string;
36
+ interpolateUrl(url: string, path?: Record<string, any>): string;
37
37
  }
38
38
  //# sourceMappingURL=urlBuilder.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"urlBuilder.d.ts","sourceRoot":"","sources":["../src/urlBuilder.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;;;;;;GAOG;AACH,qBAAa,UAAW,YAAW,cAAc;IAC/C,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;;;;;OAQG;IACH,KAAK,CACH,GAAG,EAAE,MAAM,EACX,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAChC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAChC,MAAM;IAYT;;;;;;;OAOG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;CAWtE"}
1
+ {"version":3,"file":"urlBuilder.d.ts","sourceRoot":"","sources":["../src/urlBuilder.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;;;;;;GAOG;AACH,qBAAa,UAAW,YAAW,cAAc;IAC/C,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;;;;;OAQG;IACH,KAAK,CACH,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC1B,MAAM;IAYT;;;;;;;OAOG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;CAWhE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Core library providing basic HTTP client functionality for Fetcher",
5
5
  "keywords": [
6
6
  "fetch",