soon-fetch 0.0.1 → 0.0.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
@@ -12,60 +12,59 @@
12
12
  > - 💡 smart type tips with Typescript
13
13
 
14
14
  - [Example](#example)
15
- - [API Reference](#api-reference)
16
- - [Create Instance](#create-instance)
17
- - [Request](#request)
18
- - [Response](#response)
15
+
19
16
  - [Features](#features)
20
17
  - [Shortcut](#shortcut)
21
18
  - [Restful Url Params](#restful-url-params)
22
19
  - [Timeout](#timeout)
23
20
  - [Rapid Define APIs](#rapid-define-apis)
21
+ - [API Reference](#api-reference)
22
+ - [Create Instance](#create-instance)
23
+ - [Request](#request)
24
+ - [Response](#response)
24
25
  - [Support Me](#support-me)
25
26
 
26
27
  ### Example
28
+
27
29
  > [github: soon-admin-vue3 ](https://github.com/leafio/soon-admin-vue3)
28
30
 
29
31
  ```typescript
30
- export const soon = createSoon({
31
- baseURL: baseURL,
32
- defaultOptions:()=> ({
32
+ export const soon = createSoon<SoonOptions>({
33
+ baseURL: "/api",
34
+ defaultOptions: () => ({
33
35
  timeout: 20 * 1000,
36
+ headers: new Headers({
37
+ Authorization: localStorage.getItem("token") ?? "",
38
+ }),
34
39
  }),
35
- beforeRequest: (options) => {
36
- options.headers.append(
37
- "Authorization",
38
- localStorage.getItem("token") ?? ""
39
- );
40
- },
41
- afterResponse: async (result, resolve, reject ) => {
40
+ afterResponse: async (result, resolve, reject) => {
42
41
  const res = result.response;
43
42
  if (res) {
44
43
  if (res.ok) {
45
- const contentType = res.headers.get("content-type");
46
- if (!contentType?.includes("json")) {
47
- resolve(res);
48
- } else {
44
+ if (res.headers.get("content-type")?.includes("json")) {
49
45
  const body = await res.json();
50
46
  if (body.code === 0) {
51
47
  resolve(body.data);
52
48
  } else {
53
- console.log(res);
54
- toast.error(body.err);
55
- reject(res.body);
49
+ toast.error(body.err ?? "Invalid JSON Response");
50
+ reject(body.err);
56
51
  }
52
+ } else {
53
+ resolve(res);
57
54
  }
58
55
  } else if (res.status === 401) {
59
56
  localStorage.removeItem("token");
60
57
  location.href = "/login";
58
+ } else {
59
+ toast.error(res.statusText);
60
+ reject(res.statusText);
61
61
  }
62
- toast.error(res.statusText);
63
- reject();
64
62
  } else if (result.isTimeout) {
65
- toast.error("Timeout");
63
+ toast.error(t("tip.requestTimeout"));
66
64
  } else if (result.error) {
67
65
  toast.error(result.error);
68
66
  }
67
+ reject(result.error);
69
68
  },
70
69
  });
71
70
 
@@ -90,6 +89,61 @@ login({ username: "admin", password: "123" }).then((res) => {
90
89
  });
91
90
  ```
92
91
 
92
+ ### Features
93
+
94
+ ##### Shortcut
95
+
96
+ ```typescript
97
+ soon.get(url, options);
98
+ soon.post(url, options);
99
+ soon.put(url, options);
100
+ soon.patch(url, options);
101
+ soon.delete(url, options);
102
+ soon.head(url, options);
103
+ soon.options(url, options);
104
+ ```
105
+
106
+ ##### Restful Url Params
107
+
108
+ url like /:key , will handle the key
109
+
110
+ ```typescript
111
+ soon.get("/api/user/:id", { params: { id: 1 } });
112
+ // api/user/1
113
+ soon.get("/api/:job/:year", { params: { job: "engineer", year: 5 } });
114
+ //api/engineer/5
115
+ ```
116
+
117
+ ##### Timeout
118
+
119
+ ```typescript
120
+ //** the request level timeout, will override the instance level timeout */
121
+ soon.get(url, { timeout: 1000 * 20 });
122
+ ```
123
+
124
+ ##### Rapid Define APIs
125
+
126
+ ```typescript
127
+ //can be GET POST PATCH PUT DELETE
128
+ //GET data=>query,other method data=>body
129
+ soon.API(url:string).POST<RequestType,ResponseType>()
130
+
131
+ //define an api
132
+ export const getUserInfo=soon.API('/user/:id').GET()
133
+ //then use in any where
134
+ getUserInfo({id:2})
135
+ .then(res=>console.log(res))
136
+ .catch(err=>console.log(err))
137
+
138
+ //with typescript,
139
+ export const login=soon.API('/user/login')
140
+ .POST<{username:string,password:string},{token:string}>()
141
+ //the develop tools will have type tips for request and response
142
+ login({username:'admin',password:'123'}).then(res=>{
143
+ localStorage.setItem('token', res.token);
144
+ })
145
+ ```
146
+
93
147
  ### API Reference
94
148
 
95
149
  ##### Create Instance
@@ -106,11 +160,15 @@ export type SoonInit<Options> = {
106
160
  //**url prefix */
107
161
  baseURL?: string;
108
162
  /**the fetch http options */
109
- defaultOptions?:()=> Options;
163
+ defaultOptions?: () => Options;
110
164
  /** can modify the fetch options before been handled*/
111
165
  beforeRequest?: (options: Options & { headers: Headers }) => void;
112
166
  /** can modify the response after fetched and promise resolved */
113
- afterResponse?: (result: SoonResult<Options>, resolve: (value: any) => void, reject: (reason?: any) => void) => Promise<void>;
167
+ afterResponse?: (
168
+ result: SoonResult<Options>,
169
+ resolve: (value: any) => void,
170
+ reject: (reason?: any) => void
171
+ ) => Promise<void>;
114
172
  };
115
173
  ```
116
174
 
@@ -182,61 +240,6 @@ type SoonOptions = {
182
240
 
183
241
  Default : return raw fetch Response , you can customize it in afterResponse params of createSoon
184
242
 
185
- ### Features
186
-
187
- ##### Shortcut
188
-
189
- ```typescript
190
- soon.get(url, options);
191
- soon.post(url, options);
192
- soon.put(url, options);
193
- soon.patch(url, options);
194
- soon.delete(url, options);
195
- soon.head(url, options);
196
- soon.options(url, options);
197
- ```
198
-
199
- ##### Restful Url Params
200
-
201
- url like /:key , will handle the key
202
-
203
- ```typescript
204
- soon.get("/api/user/:id", { params: { id: 1 } });
205
- // api/user/1
206
- soon.get("/api/:job/:year", { params: { job: "engineer", year: 5 } });
207
- //api/engineer/5
208
- ```
209
-
210
- ##### Timeout
211
-
212
- ```typescript
213
- //** the request level timeout, will override the instance level timeout */
214
- soon.get(url, { timeout: 1000 * 20 });
215
- ```
216
-
217
- ##### Rapid Define APIs
218
-
219
- ```typescript
220
- //can be GET POST PATCH PUT DELETE
221
- //GET data=>query,other method data=>body
222
- soon.API(url:string).POST<RequestType,ResponseType>()
223
-
224
- //define an api
225
- export const getUserInfo=soon.API('/user/:id').GET()
226
- //then use in any where
227
- getUserInfo({id:2})
228
- .then(res=>console.log(res))
229
- .catch(err=>console.log(err))
230
-
231
- //with typescript,
232
- export const login=soon.API('/user/login')
233
- .POST<{username:string,password:string},{token:string}>()
234
- //the develop tools will have type tips for request and response
235
- login({username:'admin',password:'123'}).then(res=>{
236
- localStorage.setItem('token', res.token);
237
- })
238
- ```
239
-
240
243
  ### Support Me
241
244
 
242
245
  If you like this library , you can give a **start** on github.
@@ -258,61 +261,61 @@ Email: leafnote@outlook.com
258
261
  > - 💡 用 typescript 有智能类型提醒
259
262
 
260
263
  - [示例](#示例)
261
- - [API 参考](#api参考)
262
-
263
- - [创建实例](#创建实例)
264
- - [请求](#请求)
265
- - [响应](#响应)
266
264
 
267
265
  - [特别功能](#特别功能)
268
266
  - [快捷方法](#快捷方法)
269
267
  - [Restful Url 参数自动处理](#restful-url-参数自动处理)
270
268
  - [超时](#超时)
271
269
  - [快速定义 API](#快速定义-api)
270
+ - [API 参考](#api参考)
271
+
272
+ - [创建实例](#创建实例)
273
+ - [请求](#请求)
274
+ - [响应](#响应)
275
+
272
276
  - [支持一下](#支持一下)
273
277
 
274
278
  ### 示例
279
+
275
280
  > [github: soon-admin-vue3 ](https://github.com/leafio/soon-admin-vue3)
281
+
276
282
  ```typescript
277
283
  export const soon = createSoon<SoonOptions>({
278
- baseURL: baseURL,
279
- defaultOptions:()=> ({
284
+ baseURL: "/api",
285
+ defaultOptions: () => ({
280
286
  timeout: 20 * 1000,
287
+ headers: new Headers({
288
+ Authorization: localStorage.getItem("token") ?? "",
289
+ }),
281
290
  }),
282
- beforeRequest: (options) => {
283
- options.headers.append(
284
- "Authorization",
285
- localStorage.getItem("token") ?? ""
286
- );
287
- },
288
- afterResponse: async (result, resolve, reject ) => {
291
+ afterResponse: async (result, resolve, reject) => {
289
292
  const res = result.response;
290
293
  if (res) {
291
294
  if (res.ok) {
292
- const contentType = res.headers.get("content-type");
293
- if (!contentType?.includes("json")) {
294
- resolve(res);
295
- } else {
295
+ if (res.headers.get("content-type")?.includes("json")) {
296
296
  const body = await res.json();
297
297
  if (body.code === 0) {
298
298
  resolve(body.data);
299
299
  } else {
300
- console.log(res);
301
- toast.error(body.err);
302
- reject(res.body);
300
+ toast.error(body.err ?? "Invalid JSON Response");
301
+ reject(body.err);
303
302
  }
303
+ } else {
304
+ resolve(res);
304
305
  }
305
306
  } else if (res.status === 401) {
306
307
  localStorage.removeItem("token");
307
308
  location.href = "/login";
309
+ } else {
310
+ toast.error(res.statusText);
311
+ reject(res.statusText);
308
312
  }
309
- toast.error(res.statusText);
310
- reject();
311
313
  } else if (result.isTimeout) {
312
- toast.error("请求超时");
314
+ toast.error(t("tip.requestTimeout"));
313
315
  } else if (result.error) {
314
316
  toast.error(result.error);
315
317
  }
318
+ reject(result.error);
316
319
  },
317
320
  });
318
321
 
@@ -337,6 +340,61 @@ login({ username: "admin", password: "123" }).then((res) => {
337
340
  });
338
341
  ```
339
342
 
343
+ ### 特别功能
344
+
345
+ ##### 快捷方法
346
+
347
+ ```typescript
348
+ soon.get(url, options);
349
+ soon.post(url, options);
350
+ soon.put(url, options);
351
+ soon.patch(url, options);
352
+ soon.delete(url, options);
353
+ soon.head(url, options);
354
+ soon.options(url, options);
355
+ ```
356
+
357
+ ###### Restful Url 参数自动处理
358
+
359
+ url 包含 /:key 会解析匹配 key
360
+
361
+ ```typescript
362
+ soon.get("/api/user/:id", { params: { id: 1 } });
363
+ // api/user/1
364
+ soon.get("/api/:job/:year", { params: { job: "engineer", year: 5 } });
365
+ //api/engineer/5
366
+ ```
367
+
368
+ ##### 超时
369
+
370
+ ```typescript
371
+ //** 请求级超时, 会覆盖实例级超时 */
372
+ soon.get(url, { timeout: 1000 * 20 });
373
+ ```
374
+
375
+ ##### 快速定义 API
376
+
377
+ ```typescript
378
+ //可以是 GET POST PATCH PUT DELETE
379
+ //GET 请求数据传递至query,其他方法请求数据传递至body
380
+ soon.API(url:string).POST<RequestType,ResponseType>()
381
+
382
+ //定义一个api
383
+ export const getUserInfo=soon.API('/user/:id').GET()
384
+ //使用
385
+ getUserInfo({id:2})
386
+ .then(res=>console.log(res))
387
+ .catch(err=>console.log(err))
388
+
389
+ //用typescript,
390
+ export const login=soon.API('/user/login')
391
+ .POST<{username:string,password:string},{token:string}>()
392
+ //开发工具会有请求和响应的智能提醒
393
+ login({username:'admin',password:'123'}).then(res=>{
394
+ localStorage.setItem('token', res.token);
395
+ })
396
+ ```
397
+
340
398
  ### API 参考
341
399
 
342
400
  ##### 创建实例
@@ -352,11 +410,15 @@ declare function createSoon<Options extends SoonOptions = SoonOptions>(
352
410
  export type SoonInit<Options> = {
353
411
  baseURL?: string;
354
412
  //默认的options
355
- defaultOptions?:()=> Options;
413
+ defaultOptions?: () => Options;
356
414
  //在请求前对options的处理
357
415
  beforeRequest?: (options: Options & { headers: Headers }) => void;
358
416
  //在请求后对Response的处理
359
- afterResponse?: (result: SoonResult<Options>, resolve: (value: any) => void, reject: (reason?: any) => void) => Promise<void>;
417
+ afterResponse?: (
418
+ result: SoonResult<Options>,
419
+ resolve: (value: any) => void,
420
+ reject: (reason?: any) => void
421
+ ) => Promise<void>;
360
422
  };
361
423
  ```
362
424
 
@@ -439,69 +501,14 @@ type SoonOptions = {
439
501
 
440
502
  默认为原生 fetch 的 Response ,可在 createSoon 的 afterResponse 里自定义处理 Response
441
503
 
442
- ### 特别功能
443
-
444
- ##### 快捷方法
445
-
446
- ```typescript
447
- soon.get(url, options);
448
- soon.post(url, options);
449
- soon.put(url, options);
450
- soon.patch(url, options);
451
- soon.delete(url, options);
452
- soon.head(url, options);
453
- soon.options(url, options);
454
- ```
455
-
456
- ###### Restful Url 参数自动处理
457
-
458
- url 包含 /:key 会解析匹配 key
459
-
460
- ```typescript
461
- soon.get("/api/user/:id", { params: { id: 1 } });
462
- // api/user/1
463
- soon.get("/api/:job/:year", { params: { job: "engineer", year: 5 } });
464
- //api/engineer/5
465
- ```
466
-
467
- ##### 超时
468
-
469
- ```typescript
470
- //** 请求级超时, 会覆盖实例级超时 */
471
- soon.get(url, { timeout: 1000 * 20 });
472
- ```
473
-
474
- ##### 快速定义 API
475
-
476
- ```typescript
477
- //可以是 GET POST PATCH PUT DELETE
478
- //GET 请求数据传递至query,其他方法请求数据传递至body
479
- soon.API(url:string).POST<RequestType,ResponseType>()
480
-
481
- //定义一个api
482
- export const getUserInfo=soon.API('/user/:id').GET()
483
- //使用
484
- getUserInfo({id:2})
485
- .then(res=>console.log(res))
486
- .catch(err=>console.log(err))
487
-
488
- //用typescript,
489
- export const login=soon.API('/user/login')
490
- .POST<{username:string,password:string},{token:string}>()
491
- //开发工具会有请求和响应的智能提醒
492
- login({username:'admin',password:'123'}).then(res=>{
493
- localStorage.setItem('token', res.token);
494
- })
495
- ```
496
504
  ### 支持一下
497
505
 
498
- 喜欢soon-fetch的话 , 在github上给个 **star** 吧.
506
+ 喜欢 soon-fetch 的话 , 在 github 上给个 **star** 吧.
499
507
  Email: leafnote@outlook.com
500
508
 
501
509
  > 我目前在找前端的工作,位置上海。有岗位机会的话,可以联系我。
502
510
 
503
-
504
- [English](#soon-is-a-lightweight-http-request-library-based-on-vanilla-fetch-with-typescript) | [中文](#soon-是用-ts-对原生-fetch-的轻量封装)
511
+ [English](#soon-fetch-is-a-lightweight-http-request-library-based-on-vanilla-fetch-with-typescript) | [中文](#soon-fetch-是用-ts-对原生-fetch-的轻量封装)
505
512
 
506
513
  <!-- omit in toc -->
507
514
 
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";function e(e,t,n,s){return new(n||(n=Promise))((function(o,r){function i(e){try{c(s.next(e))}catch(e){r(e)}}function a(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=e=>{var t;const n=[];return null===(t=e.match(/\:([^:\/\d]+)\/?/g))||void 0===t||t.forEach((e=>{n.push(e.replace(/\//g,"").replace(/:/g,""))})),n},n=(e,n)=>{const{query:s,params:o,baseURL:r}=n;let i=e.trim();let a,c;t(e).forEach((e=>{o&&(i=i.replace(":"+e,""+o[e]))}));let u=[i];const l="http";if(0!==i.indexOf(l)){if(0!==(null==r?void 0:r.indexOf(l))){c=!0;let e=r;(null==r?void 0:r.endsWith("/"))&&(e=null==e?void 0:e.slice(0,-1)),e+=i.startsWith("/")?i:"/"+i,u=[e]}let e=c?`${l}://t.c`:r;e&&u.push(e)}let d;a=new URL(...u);const f=[];s&&Object.keys(s).forEach((e=>{const t=s[e];(Array.isArray(t)?t:[t]).forEach((t=>{f.push([e,null!=t?t:""])}))})),d=new URLSearchParams([...Array.from(a.searchParams.entries()),...f]);let h=(c?"":a.origin)+a.pathname;return d&&(h=h+"?"+d),h},s=(...e)=>{const t=new Headers;return e.forEach((e=>{e&&e.forEach(((e,n)=>{t.set(n,e)}))})),t};exports.createSoon=function(o={}){const r={};r.baseInit=o;const i=(t,o)=>function(t,o,r){const i=null==r?void 0:r.defaultOptions,a=i?i():void 0;let c=s(null==a?void 0:a.headers,null==o?void 0:o.headers),u=Object.assign({},a,o,{headers:c});const{beforeRequest:l,afterResponse:d}=r||{};l&&l(u);let f=u.timeout;const h=[];f&&h.push(AbortSignal.timeout(f));const p=u.signal;p&&h.push(p),u.signal=AbortSignal.any(h);const b=(t,n,s)=>e(this,void 0,void 0,(function*(){d&&(yield d(t,n,s));const e=t.response;e&&n(e),s(t)}));return new Promise(((s,o)=>e(this,void 0,void 0,(function*(){let e=n(t,Object.assign(Object.assign({},u),{baseURL:null==r?void 0:r.baseURL})),i=!1;const a=u.body;a&&(a instanceof Blob||a instanceof ArrayBuffer||a instanceof FormData||"string"==typeof a||(i=!0,u.body=JSON.stringify(a))),i&&u.headers.set("Content-Type","application/json");const c=new Request(e,u);let l={request:c,options:u};try{const e=yield fetch(c);l.response=e,b(l,s,o)}catch(e){"TimeoutError"===(null==e?void 0:e.name)&&(l.isTimeout=!0),b(Object.assign(Object.assign({},l),{error:e}),s,o)}}))))}(t,o,r.baseInit),a=["get","post","put","delete","patch"];return[...a,"head","options"].forEach((e=>{r[e]=(t,n)=>i(t,Object.assign({method:e},n))})),r.request=i,r.API=(e,n)=>{const s={},o=!!t(e).length;return a.forEach((t=>{const r=t.toUpperCase();s[r]=()=>(...s)=>{let[r,a]=s;const c="get"===t?"query":"body";return i(e,Object.assign(Object.assign({method:t},n),{params:o?r:void 0,[c]:o?a:r}))}})),s},r};
1
+ "use strict";function e(e,t,n,s){return new(n||(n=Promise))((function(o,r){function a(e){try{c(s.next(e))}catch(e){r(e)}}function i(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}c((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=e=>{var t;const n=[];return null===(t=e.match(/\:([^:\/\d]+)\/?/g))||void 0===t||t.forEach((e=>{n.push(e.replace(/\//g,"").replace(/:/g,""))})),n},n=(e,n)=>{const{query:s,params:o,baseURL:r}=n;let a=e.trim();let i,c;t(e).forEach((e=>{o&&(a=a.replace(":"+e,""+o[e]))}));const u="http",l=e=>(null==e?void 0:e.endsWith("/"))?e.slice(0,-1):null!=e?e:"",d=e=>{let t=null!=e?e:"";return e&&(t=l(t),e.startsWith("/")||(t="/"+t)),t};let f,h=a;if(0!==a.indexOf(u)){let e=l(r);0!==(null==r?void 0:r.indexOf(u))&&(c=!0,e=`${u}://t.c`+d(r)),h=e+d(a)}i=new URL(h);const p=[];s&&Object.keys(s).forEach((e=>{const t=s[e];(Array.isArray(t)?t:[t]).forEach((t=>{p.push([e,null!=t?t:""])}))})),f=new URLSearchParams([...Array.from(i.searchParams.entries()),...p]);let b=(c?"":i.origin)+i.pathname;return f.size&&(b=b+"?"+f),b},s=(...e)=>{const t=new Headers;return e.forEach((e=>{e&&e.forEach(((e,n)=>{t.set(n,e)}))})),t};exports.createSoon=function(o={}){const r={};r.baseInit=o;const a=(t,o)=>function(t,o,r){const a=null==r?void 0:r.defaultOptions,i=a?a():void 0;let c=s(null==i?void 0:i.headers,null==o?void 0:o.headers),u=Object.assign({},i,o,{headers:c});const{beforeRequest:l,afterResponse:d}=r||{};l&&l(u);let f=u.timeout;const h=[];f&&h.push(AbortSignal.timeout(f));const p=u.signal;p&&h.push(p),u.signal=AbortSignal.any(h);const b=(t,n,s)=>e(this,void 0,void 0,(function*(){d&&(yield d(t,n,s));const e=t.response;e&&n(e),s(t)}));return new Promise(((s,o)=>e(this,void 0,void 0,(function*(){let e=n(t,Object.assign(Object.assign({},u),{baseURL:null==r?void 0:r.baseURL})),a=!1;const i=u.body;i&&(i instanceof Blob||i instanceof ArrayBuffer||i instanceof FormData||"string"==typeof i||(a=!0,u.body=JSON.stringify(i))),a&&u.headers.set("Content-Type","application/json");const c=new Request(e,u);let l={request:c,options:u};try{const e=yield fetch(c);l.response=e,b(l,s,o)}catch(e){"TimeoutError"===(null==e?void 0:e.name)&&(l.isTimeout=!0),b(Object.assign(Object.assign({},l),{error:e}),s,o)}}))))}(t,o,r.baseInit),i=["get","post","put","delete","patch"];return[...i,"head","options"].forEach((e=>{r[e]=(t,n)=>a(t,Object.assign({method:e},n))})),r.request=a,r.API=(e,n)=>{const s={},o=!!t(e).length;return i.forEach((t=>{const r=t.toUpperCase();s[r]=()=>(...s)=>{let[r,i]=s;const c="get"===t?"query":"body";return a(e,Object.assign(Object.assign({method:t},n),{params:o?r:void 0,[c]:o?i:r}))}})),s},r};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function e(e,t,n,o){return new(n||(n=Promise))((function(s,r){function i(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=e=>{var t;const n=[];return null===(t=e.match(/\:([^:\/\d]+)\/?/g))||void 0===t||t.forEach((e=>{n.push(e.replace(/\//g,"").replace(/:/g,""))})),n},n=(e,n)=>{const{query:o,params:s,baseURL:r}=n;let i=e.trim();let a,c;t(e).forEach((e=>{s&&(i=i.replace(":"+e,""+s[e]))}));let u=[i];const l="http";if(0!==i.indexOf(l)){if(0!==(null==r?void 0:r.indexOf(l))){c=!0;let e=r;(null==r?void 0:r.endsWith("/"))&&(e=null==e?void 0:e.slice(0,-1)),e+=i.startsWith("/")?i:"/"+i,u=[e]}let e=c?`${l}://t.c`:r;e&&u.push(e)}let d;a=new URL(...u);const f=[];o&&Object.keys(o).forEach((e=>{const t=o[e];(Array.isArray(t)?t:[t]).forEach((t=>{f.push([e,null!=t?t:""])}))})),d=new URLSearchParams([...Array.from(a.searchParams.entries()),...f]);let h=(c?"":a.origin)+a.pathname;return d&&(h=h+"?"+d),h},o=(...e)=>{const t=new Headers;return e.forEach((e=>{e&&e.forEach(((e,n)=>{t.set(n,e)}))})),t};function s(s={}){const r={};r.baseInit=s;const i=(t,s)=>function(t,s,r){const i=null==r?void 0:r.defaultOptions,a=i?i():void 0;let c=o(null==a?void 0:a.headers,null==s?void 0:s.headers),u=Object.assign({},a,s,{headers:c});const{beforeRequest:l,afterResponse:d}=r||{};l&&l(u);let f=u.timeout;const h=[];f&&h.push(AbortSignal.timeout(f));const p=u.signal;p&&h.push(p),u.signal=AbortSignal.any(h);const b=(t,n,o)=>e(this,void 0,void 0,(function*(){d&&(yield d(t,n,o));const e=t.response;e&&n(e),o(t)}));return new Promise(((o,s)=>e(this,void 0,void 0,(function*(){let e=n(t,Object.assign(Object.assign({},u),{baseURL:null==r?void 0:r.baseURL})),i=!1;const a=u.body;a&&(a instanceof Blob||a instanceof ArrayBuffer||a instanceof FormData||"string"==typeof a||(i=!0,u.body=JSON.stringify(a))),i&&u.headers.set("Content-Type","application/json");const c=new Request(e,u);let l={request:c,options:u};try{const e=yield fetch(c);l.response=e,b(l,o,s)}catch(e){"TimeoutError"===(null==e?void 0:e.name)&&(l.isTimeout=!0),b(Object.assign(Object.assign({},l),{error:e}),o,s)}}))))}(t,s,r.baseInit),a=["get","post","put","delete","patch"];return[...a,"head","options"].forEach((e=>{r[e]=(t,n)=>i(t,Object.assign({method:e},n))})),r.request=i,r.API=(e,n)=>{const o={},s=!!t(e).length;return a.forEach((t=>{const r=t.toUpperCase();o[r]=()=>(...o)=>{let[r,a]=o;const c="get"===t?"query":"body";return i(e,Object.assign(Object.assign({method:t},n),{params:s?r:void 0,[c]:s?a:r}))}})),o},r}export{s as createSoon};
1
+ function e(e,t,n,s){return new(n||(n=Promise))((function(o,r){function a(e){try{c(s.next(e))}catch(e){r(e)}}function i(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}c((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=e=>{var t;const n=[];return null===(t=e.match(/\:([^:\/\d]+)\/?/g))||void 0===t||t.forEach((e=>{n.push(e.replace(/\//g,"").replace(/:/g,""))})),n},n=(e,n)=>{const{query:s,params:o,baseURL:r}=n;let a=e.trim();let i,c;t(e).forEach((e=>{o&&(a=a.replace(":"+e,""+o[e]))}));const u="http",l=e=>(null==e?void 0:e.endsWith("/"))?e.slice(0,-1):null!=e?e:"",d=e=>{let t=null!=e?e:"";return e&&(t=l(t),e.startsWith("/")||(t="/"+t)),t};let f,h=a;if(0!==a.indexOf(u)){let e=l(r);0!==(null==r?void 0:r.indexOf(u))&&(c=!0,e=`${u}://t.c`+d(r)),h=e+d(a)}i=new URL(h);const p=[];s&&Object.keys(s).forEach((e=>{const t=s[e];(Array.isArray(t)?t:[t]).forEach((t=>{p.push([e,null!=t?t:""])}))})),f=new URLSearchParams([...Array.from(i.searchParams.entries()),...p]);let b=(c?"":i.origin)+i.pathname;return f.size&&(b=b+"?"+f),b},s=(...e)=>{const t=new Headers;return e.forEach((e=>{e&&e.forEach(((e,n)=>{t.set(n,e)}))})),t};function o(o={}){const r={};r.baseInit=o;const a=(t,o)=>function(t,o,r){const a=null==r?void 0:r.defaultOptions,i=a?a():void 0;let c=s(null==i?void 0:i.headers,null==o?void 0:o.headers),u=Object.assign({},i,o,{headers:c});const{beforeRequest:l,afterResponse:d}=r||{};l&&l(u);let f=u.timeout;const h=[];f&&h.push(AbortSignal.timeout(f));const p=u.signal;p&&h.push(p),u.signal=AbortSignal.any(h);const b=(t,n,s)=>e(this,void 0,void 0,(function*(){d&&(yield d(t,n,s));const e=t.response;e&&n(e),s(t)}));return new Promise(((s,o)=>e(this,void 0,void 0,(function*(){let e=n(t,Object.assign(Object.assign({},u),{baseURL:null==r?void 0:r.baseURL})),a=!1;const i=u.body;i&&(i instanceof Blob||i instanceof ArrayBuffer||i instanceof FormData||"string"==typeof i||(a=!0,u.body=JSON.stringify(i))),a&&u.headers.set("Content-Type","application/json");const c=new Request(e,u);let l={request:c,options:u};try{const e=yield fetch(c);l.response=e,b(l,s,o)}catch(e){"TimeoutError"===(null==e?void 0:e.name)&&(l.isTimeout=!0),b(Object.assign(Object.assign({},l),{error:e}),s,o)}}))))}(t,o,r.baseInit),i=["get","post","put","delete","patch"];return[...i,"head","options"].forEach((e=>{r[e]=(t,n)=>a(t,Object.assign({method:e},n))})),r.request=a,r.API=(e,n)=>{const s={},o=!!t(e).length;return i.forEach((t=>{const r=t.toUpperCase();s[r]=()=>(...s)=>{let[r,i]=s;const c="get"===t?"query":"body";return a(e,Object.assign(Object.assign({method:t},n),{params:o?r:void 0,[c]:o?i:r}))}})),s},r}export{o as createSoon};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soon-fetch",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "a lightweight request library based on fetch with TS prompt",
5
5
  "homepage": "https://github.com/leafio/soon-fetch",
6
6
  "main": "./dist/index.cjs.js",