kbfetch 0.0.27 → 1.0.1

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
@@ -6,16 +6,26 @@
6
6
  import kbfetch from 'kbfetch'
7
7
  kbfetch.get('https://api.example.com/data', { id: 1 })
8
8
  // OR
9
- kbfetch.g('https://api.example.com/data', {
10
- params: { id: 1 }
11
- // 其他kbFetchInit属性
12
- })
9
+ kbfetch.g('https://api.example.com/data', { params: { id: 1 } })
13
10
  ```
14
11
 
15
12
  发起 POST 请求的示例:
16
13
 
17
14
  ```js
18
15
  kbfetch.post('https://api.example.com/data', { id: 1 })
16
+ // OR需要query参数
17
+ kbfetch.post('https://api.example.com/data', { id: 1 }, { params: { qa: 1 } })
18
+ // OR
19
+ kbfetch.p('https://api.example.com/data', { params: { qa: 1 }, body: { id: 1 } })
20
+ ```
21
+
22
+ 发起 其他method 请求的示例:
23
+
24
+ ```js
25
+ // e.g. 1
26
+ kbfetch.p('https://baidu.com', { method: 'PUT' })
27
+ // e.g. 2
28
+ kbfetch.g('https://baidu.com', { method: 'PATCH' })
19
29
  ```
20
30
 
21
31
  取消请求示例:
@@ -26,23 +36,55 @@ const ft = kbfetch.post('https://api.example.com/data', { id: 1 }, { canAbort: t
26
36
  ft.abort()
27
37
  ```
28
38
 
39
+ `or`
40
+
29
41
  ```js
30
42
  const ft = kbfetch.g('https://api.example.com/data', { params: { id: 1 }, timeout: 0 })
31
43
  ft.abort()
32
44
  ```
33
45
 
46
+ 设置公共参数比如token
47
+
48
+ ```js
49
+ kbfetch.baseHeaders = { token: 'XXX' }
50
+
51
+ kbfetch.baseParams = { access_token: 'xxx' }
52
+
53
+ kbfetch.baseBody = { access_token: 'xxx' }
54
+ ```
55
+
56
+ ### 方法汇总
57
+
58
+ ```
59
+ get: (url: string, params?: Record<string, any>, init?: KbFetchInit)
60
+
61
+ g: (url: string, init?: KbFetchInit & { params?: Record<string, any> })
62
+
63
+ post: (url: string, body?: Record<string, any>, init?: KbFetchInit)
64
+
65
+ p: (url: string, init?: KbFetchInit)
66
+
67
+ uploadFile: (url: string, file: File, init?: KbFetchInit)
68
+
69
+ 其他method可以通过p方法或者g方法,实现
70
+ ```
71
+
34
72
  ### 自定义选项
35
73
 
36
74
  `KbFetchInit` 类型扩展了标准的 `RequestInit`,添加了一些可选的便捷属性:
37
75
 
38
- - `baseUrl` - API的基础网址
76
+ - `baseUrl` - API地址的公共前缀
77
+ - `baseHeaders` - 公共的header,如token
78
+ - `baseParams` - 公共的params,如企业微信的access_token,没有放在header里面,可以在这里设置
79
+ - `baseBody` - 公共body
39
80
  - `timeout` - 请求超时时间(毫秒)
40
81
  - `before` - 修改/记录请求参数的回调函数
41
82
  - `parser` - 在返回resolve前解析响应的回调函数
42
83
  - `after` - 响应结果的回调函数
43
84
 
44
85
  ```typescript
45
- import kbfetch, { createKbFetch } from 'kbfetch'
86
+ import kbfetch, { createKbFetch, kbfc } from 'kbfetch'
87
+ // kbfc等同于kbfetch
46
88
  // 请求单独配置
47
89
  kbfetch.post(url, data, kbFetchInit)
48
90
  kbfetch.get(url, params, kbFetchInit)
package/dist/index.js CHANGED
@@ -18,57 +18,83 @@ var help = {
18
18
  const headers = new Headers;
19
19
  Object.entries(obj).forEach(([k, v]) => headers.append(k, v));
20
20
  return headers;
21
- }
21
+ },
22
+ urlWithProtocol: (url) => url.startsWith("http://") || url.startsWith("https://"),
23
+ addProtocol: (url) => !url || !global.location || help.urlWithProtocol(url) ? url : location.protocol + url,
24
+ objPick: (obj, keys) => Object.fromEntries(keys.map((key) => [key, obj[key]])),
25
+ objSetDefVal: (obj, key, def) => def && (obj[key] = Object.assign({}, def, obj[key]))
22
26
  };
23
27
  var help_default = help;
24
28
 
25
29
  // index.ts
26
30
  var defaultKbFetch = {
27
- baseUrl: "",
28
31
  before: (init) => init,
29
32
  after: (res) => res.then((res2) => res2.data),
30
33
  parser: help_default.parseResBody,
31
34
  timeout: -1,
32
35
  do: function(url, init) {
33
- const _t = this;
34
- let { before = _t.before, ..._init } = init || {};
35
- _init = before(_init);
36
- let { parser = _t.parser, after = _t.after, baseUrl = _t.baseUrl, timeout = _t.timeout, canAbort, headers, ...requestInit } = _init;
36
+ const { baseUrl, baseHeaders, baseParams, baseBody } = this;
37
+ const defOpts = help_default.objPick(this, ["before", "parser", "after", "timeout"]);
38
+ const _init = Object.assign(defOpts, init);
39
+ help_default.objSetDefVal(_init, "headers", baseHeaders);
40
+ help_default.objSetDefVal(_init, "params", baseParams);
41
+ baseBody && _init.headers?.["Content-Type"] === "application/json" && help_default.objSetDefVal(_init, "body", baseBody);
42
+ let { parser, after, timeout, canAbort, ...requestInit } = _init.before(_init) || _init;
37
43
  let abortController;
38
44
  let timeoutIns;
39
45
  if (timeout > 0 || canAbort) {
40
46
  abortController = new AbortController;
47
+ Object.assign(requestInit, { signal: abortController.signal });
41
48
  abortController.signal.onabort = () => clearTimeout(timeoutIns);
42
49
  timeoutIns = setTimeout(() => {
43
50
  abortController.abort();
44
51
  }, timeout);
45
52
  }
46
- abortController && Object.assign(requestInit, { signal: abortController.signal });
47
- headers && Object.assign(requestInit, { headers: help_default.obj2header(headers) });
48
- if (!url.startsWith("http://") && !url.startsWith("https://"))
49
- url = baseUrl + url;
53
+ if (requestInit.params)
54
+ url = help_default.synthesizeUrlWithParams(url, requestInit.params);
55
+ if (requestInit.body && requestInit.body.constructor.name === "Object" && requestInit.headers?.["Content-Type"] !== "application/json") {
56
+ requestInit.headers ||= {};
57
+ requestInit.headers["Content-Type"] == "application/json";
58
+ requestInit.body = JSON.stringify(requestInit.body);
59
+ }
60
+ requestInit.headers && (requestInit.headers = help_default.obj2header(requestInit.headers));
61
+ url = help_default.urlWithProtocol(url) ? url : help_default.addProtocol(baseUrl) + url;
50
62
  const response = fetch(url, requestInit).then(async (respnse) => Object.assign(respnse, { data: await parser(respnse) })).finally(() => clearTimeout(timeoutIns));
51
63
  return Object.assign(after(response), {
52
64
  abort: () => abortController?.abort()
53
65
  });
54
66
  },
55
67
  get: function(url, params, init) {
56
- return this.do(help_default.synthesizeUrlWithParams(url, params), init);
68
+ params && (init ||= {}, init.params = params);
69
+ return this.do(url, init);
57
70
  },
58
71
  g: function(url, init) {
59
- const { params, ..._init } = init || {};
60
- return this.get(url, params, _init);
72
+ return this.do(url, init);
73
+ },
74
+ post: function(url, body, init) {
75
+ const _init = Object.assign({}, init, { method: "POST", body });
76
+ return this.do(url, _init);
77
+ },
78
+ p: function(url, init) {
79
+ const _init = Object.assign({}, { method: "POST" }, init);
80
+ return this.do(url, _init);
61
81
  },
62
- post: function(url, params, init) {
63
- const _init = Object.assign({}, init, { method: "POST", body: JSON.stringify(params) });
64
- _init.headers = Object.assign({}, _init.headers, { "Content-Type": "application/json" });
82
+ uploadFile: function(url, file, init) {
83
+ const form = new FormData;
84
+ form.append("file", file);
85
+ const _init = Object.assign({}, init, { method: "POST", body: form });
65
86
  return this.do(url, _init);
66
87
  }
67
88
  };
68
- var createKbFetch = (config) => ({ ...defaultKbFetch, ...config });
89
+ var createKbFetch = (config) => ({
90
+ ...defaultKbFetch,
91
+ ...config
92
+ });
69
93
  var kbfetch = defaultKbFetch;
70
94
  var kbfetch_default = kbfetch;
95
+ var kbfc = kbfetch;
71
96
  export {
97
+ kbfc,
72
98
  kbfetch_default as default,
73
99
  createKbFetch
74
100
  };
@@ -1,21 +1,21 @@
1
- type _KbFetchInit = {
2
- before?: DefaultKbFetch['before'];
3
- parser?: DefaultKbFetch['parser'];
4
- after?: DefaultKbFetch['after'];
5
- baseUrl?: string;
6
- canAbort?: boolean;
7
- flags?: Record<string, any>;
1
+ type _KbFetchInit = Pick<DefaultKbFetch, 'baseUrl' | 'baseParams' | 'baseBody' | 'before' | 'parser' | 'after' | 'timeout'> & {
2
+ canAbort: boolean;
3
+ flags: Record<string, any>;
4
+ params: Record<string, any>;
5
+ body: Record<string, any>;
8
6
  };
9
7
  export type KbFetchInit = Omit<RequestInit, 'timeout' | 'headers'> & {
10
- timeout?: number;
11
- headers?: Record<string, string>;
12
- } & _KbFetchInit;
8
+ headers?: Object;
9
+ } & Partial<_KbFetchInit>;
13
10
  type Res<T> = Promise<T> & {
14
11
  abort: () => void;
15
12
  };
16
13
  export interface DefaultKbFetch {
17
- baseUrl: string;
18
- before: (init: KbFetchInit) => KbFetchInit;
14
+ baseUrl?: string;
15
+ baseHeaders?: Record<string, any>;
16
+ baseParams?: Record<string, any>;
17
+ baseBody?: Record<string, any>;
18
+ before: <T extends any>(init: T) => T | void;
19
19
  after: (res: Promise<Response & {
20
20
  data: any;
21
21
  }>) => any;
@@ -26,11 +26,17 @@ export interface DefaultKbFetch {
26
26
  g: <T = any>(url: string, init?: KbFetchInit & {
27
27
  params?: Record<string, any>;
28
28
  }) => Res<T>;
29
- post: <T = any>(url: string, params?: Record<string, any>, init?: KbFetchInit) => Res<T>;
29
+ post: <T = any>(url: string, body?: Record<string, any>, init?: KbFetchInit) => Res<T>;
30
+ p: <T = any>(url: string, init?: KbFetchInit) => Res<T>;
31
+ uploadFile: <T = any>(url: string, file: File, init?: KbFetchInit) => Res<T>;
30
32
  }
31
33
  declare const help: {
32
34
  synthesizeUrlWithParams: (url: string, params?: Record<string, any>) => string;
33
35
  parseResBody: (res: Response) => Promise<any>;
34
- obj2header: (obj: Record<string, string>) => Headers;
36
+ obj2header: (obj: Object) => Headers;
37
+ urlWithProtocol: (url: string) => boolean;
38
+ addProtocol: (url?: string) => string;
39
+ objPick: <T extends Object, K extends keyof T>(obj: T, keys: K[]) => Pick<T, K>;
40
+ objSetDefVal: <O extends Object, K extends keyof O, D extends Object>(obj: O, key: K, def?: D) => {} & D & O[K];
35
41
  };
36
42
  export default help;
@@ -1,38 +1,36 @@
1
- import { DefaultKbFetch, KbFetchInit } from './help';
2
- export declare const createKbFetch: (config: Partial<Pick<DefaultKbFetch, 'baseUrl' | 'timeout' | 'before' | 'parser' | 'after'>>) => {
1
+ import { DefaultKbFetch } from './help';
2
+ export declare const createKbFetch: (config: Partial<Pick<DefaultKbFetch, "baseUrl" | "baseParams" | "baseBody" | "timeout" | "before" | "parser" | "after">>) => {
3
3
  after: (res: Promise<Response & {
4
4
  data: any;
5
5
  }>) => any;
6
- before: (init: KbFetchInit) => KbFetchInit;
6
+ before: <T extends any>(init: T) => T | void;
7
7
  timeout: number;
8
+ baseUrl?: string;
9
+ baseParams?: Record<string, any>;
10
+ baseBody?: Record<string, any>;
8
11
  parser: (res: Response) => any;
9
- baseUrl: string;
10
- do: <T>(url: string, init?: KbFetchInit) => Promise<T> & {
12
+ baseHeaders?: Record<string, any>;
13
+ do: <T>(url: string, init?: import("./help").KbFetchInit) => Promise<T> & {
11
14
  abort: () => void;
12
15
  };
13
- get: <T_1 = any>(url: string, params?: Record<string, any>, init?: KbFetchInit) => Promise<T_1> & {
16
+ get: <T = any>(url: string, params?: Record<string, any>, init?: import("./help").KbFetchInit) => Promise<T> & {
14
17
  abort: () => void;
15
18
  };
16
- g: <T_2 = any>(url: string, init?: Omit<RequestInit, "timeout" | "headers"> & {
17
- timeout?: number;
18
- headers?: Record<string, string>;
19
- } & {
20
- before?: (init: KbFetchInit) => KbFetchInit;
21
- parser?: (res: Response) => any;
22
- after?: (res: Promise<Response & {
23
- data: any;
24
- }>) => any;
25
- baseUrl?: string;
26
- canAbort?: boolean;
27
- flags?: Record<string, any>;
28
- } & {
19
+ g: <T = any>(url: string, init?: import("./help").KbFetchInit & {
29
20
  params?: Record<string, any>;
30
- }) => Promise<T_2> & {
21
+ }) => Promise<T> & {
31
22
  abort: () => void;
32
23
  };
33
- post: <T_3 = any>(url: string, params?: Record<string, any>, init?: KbFetchInit) => Promise<T_3> & {
24
+ post: <T = any>(url: string, body?: Record<string, any>, init?: import("./help").KbFetchInit) => Promise<T> & {
25
+ abort: () => void;
26
+ };
27
+ p: <T = any>(url: string, init?: import("./help").KbFetchInit) => Promise<T> & {
28
+ abort: () => void;
29
+ };
30
+ uploadFile: <T = any>(url: string, file: File, init?: import("./help").KbFetchInit) => Promise<T> & {
34
31
  abort: () => void;
35
32
  };
36
33
  };
37
34
  declare const kbfetch: Omit<DefaultKbFetch, "do">;
38
35
  export default kbfetch;
36
+ export declare const kbfc: Omit<DefaultKbFetch, "do">;
package/package.json CHANGED
@@ -1,31 +1,32 @@
1
1
  {
2
- "name": "kbfetch",
3
- "main": "./dist/index.js",
4
- "module": "./dist/index.js",
5
- "description": "一个轻量基于fetch封装的API请求工具库",
6
- "keywords": [
7
- "fetch",
8
- "ajax"
9
- ],
10
- "type": "module",
11
- "version": "0.0.27",
12
- "license": "MIT",
13
- "types": "./dist/typings/index.d.ts",
14
- "files": [
15
- "dist"
16
- ],
17
- "scripts": {
18
- "pub": "bun bld && bun tsc && bun patch && npm publish --registry https://registry.npmjs.org/ ; bun updatetaobao ",
19
- "patch": "git stash && npm version patch && git stash pop",
20
- "updatetaobao": "cnpm sync kbfetch",
21
- "tsc": "tsc index.ts -d --emitDeclarationOnly --declarationDir ./dist/typings",
22
- "bld": "bun build ./index.ts --outdir ./dist"
23
- },
24
- "devDependencies": {
25
- "bun-types": "latest",
26
- "typescript": "^5.2.2"
27
- },
28
- "peerDependencies": {
29
- "typescript": "^5.0.0"
30
- }
2
+ "name": "kbfetch",
3
+ "version": "1.0.1",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.js",
6
+ "devDependencies": {
7
+ "@types/node": "^20.14.10",
8
+ "bun-types": "latest",
9
+ "typescript": "^5.5.3"
10
+ },
11
+ "peerDependencies": {
12
+ "typescript": "^5.0.0"
13
+ },
14
+ "description": "一个轻量基于fetch封装的API请求工具库",
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "keywords": [
19
+ "fetch",
20
+ "ajax"
21
+ ],
22
+ "license": "MIT",
23
+ "scripts": {
24
+ "pub": "bun bld && bun tsc && npm publish --registry https://registry.npmjs.org/ ; bun updatetaobao ",
25
+ "patch": "git stash && npm version patch && git stash pop",
26
+ "updatetaobao": "cnpm sync kbfetch",
27
+ "tsc": "tsc index.ts -d --emitDeclarationOnly --declarationDir ./dist/typings",
28
+ "bld": "bun build ./index.ts --outdir ./dist"
29
+ },
30
+ "type": "module",
31
+ "types": "./dist/typings/index.d.ts"
31
32
  }