nuxt-custom-fetch 2.0.3 → 2.1.0

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
@@ -2,6 +2,8 @@
2
2
 
3
3
  简单封装 useAsyncData
4
4
 
5
+ `version > 3.0.0`
6
+
5
7
  ## 注意
6
8
 
7
9
  请求的使用形式,类似于之前的`ajax`,修改参数后,重新调用封装方法。
@@ -10,155 +12,112 @@
10
12
 
11
13
  - 在下一个 nextTick 中执行,或者设置{server: false},watch pending 变化
12
14
 
13
- 2. 因为封装后,参数的`响应式丢失`,导致`watch`无法使用
14
-
15
- 3. `refresh`和`execute`使用上也需要注意,参数不是响应式的,所以会一直是第一次请求的参数
15
+ 2. `refresh`和`execute`使用上也需要注意,参数不是响应式的,所以会一直是第一次请求的参数
16
16
 
17
+ 3. 如果传入响应式对象,使用`watch`监听,会自动重新请求
17
18
 
18
- ## HTTPOptions
19
-
20
- 实例化全局 CustomFetch
19
+ ## 安装
21
20
 
22
- ```ts
23
- {
24
- baseURL?: string
25
- handler?: (params: Record<string, any>) => Record<string, any>
26
- offline?: () => void
27
- }
21
+ ```bash
22
+ pnpm add nuxt-custom-fetch
28
23
  ```
29
24
 
30
- ### baseURL
31
-
32
- 当前实例下的 baseURL
33
-
34
- ### handler
35
-
36
- 处理 query & params 的自定义函数
37
-
38
25
  ```ts
39
- {
40
- handler({...query, ...params}) {
41
- return {}
42
- }
43
- }
26
+ // nuxt.config.ts
27
+ export default defineNuxtConfig({
28
+ modules: ['nuxt-custom-fetch']
29
+ })
44
30
  ```
45
31
 
46
- ### 请求-响应拦截
32
+ ## 使用
33
+
34
+ 实例化全局 CustomFetch
47
35
 
48
36
  ```ts
49
- {
50
- onRequest?: ({ request, options }: {
51
- request: FetchRequest
52
- options: FetchOptions
53
- }) => void
54
- onRequestError?: ({
55
- request,
56
- options,
57
- error
58
- }: {
59
- request: FetchRequest
60
- options: FetchOptions
61
- error: FetchError
62
- }) => void
63
- onResponse?: ({
64
- request,
65
- response,
66
- options
67
- }: {
68
- request: FetchRequest
69
- options: FetchOptions
70
- response: FetchResponse<any>
71
- }) => Promise<void> | void
72
- onResponseError?: ({
73
- request,
74
- response,
75
- options
76
- }: {
77
- request: FetchRequest
78
- options: FetchOptions
79
- response: FetchResponse<any>
80
- }) => void
81
- }
82
- ```
37
+ const ajax = new CustomFetch({
38
+ baseURL: ''
39
+ })
83
40
 
84
- ## 实例方法
41
+ // `http|get|post`
42
+ ajax.get('/api/user')
85
43
 
86
- `http|get|post`
44
+ ajax.post('/api/user')
87
45
 
88
- ### offline
46
+ ajax.http({
47
+ method: 'GET'
48
+ })
49
+ ```
89
50
 
90
- 客户端中,离线时调用(判断 navigator.onLine)
51
+ ## 类型
91
52
 
92
- ## ajax - 传参
53
+ ### useAsyncDataType
93
54
 
94
- ### fetchOptions
55
+ [use-async-data-type](https://nuxt.com/docs/api/composables/use-async-data#type)
95
56
 
96
57
  ```ts
97
- interface fetchOptions {
98
- baseURL?: string
58
+ export declare class CustomFetch {
59
+ baseURL: any
60
+ immutableKey: boolean
61
+ params: HTTPConfig
62
+ baseHandler: HTTPConfig['handler']
63
+ interceptors: Interceptors
64
+ offline: typeof Noop
65
+ constructor (config?: HTTPConfig)
66
+ private baseConfig
67
+ http<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config: HTTPConfig & {
68
+ method: FetchMethod
69
+ }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>
70
+ get<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config?: HTTPConfig, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>
71
+ post<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config?: HTTPConfig, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>
72
+ }
73
+
74
+ export interface OnRequestType {
75
+ request: FetchRequest
76
+ options: FetchOptions
77
+ }
78
+ export interface OnRequestErrorType {
79
+ request: FetchRequest
80
+ options: FetchOptions
81
+ error: FetchError
82
+ }
83
+ export interface OnResponseType {
84
+ request: FetchRequest
85
+ options: FetchOptions
86
+ response: FetchResponse<any>
87
+ }
88
+ export interface OnResponseErrorType {
89
+ request: FetchRequest
90
+ options: FetchOptions
91
+ response: FetchResponse<any>
92
+ }
93
+ export type FetchMethod = 'options' | 'GET' | 'POST' | 'get' | 'HEAD' | 'PATCH' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'post' | 'head' | 'patch' | 'put' | 'delete' | 'connect' | 'trace' | undefined
94
+ export interface HTTPConfig extends Omit<FetchOptions, 'method'> {
99
95
  key?: string
100
- body?: RequestInit['body'] | Record<string, any>
101
- useHandler: HTTPConfig['useHandler']
102
- handler: HTTPConfig['handler']
103
- params?: SearchParameters
104
- query?: SearchParameters
105
- parseResponse?: (responseText: string) => any
106
- responseType?: R
107
- response?: boolean
108
- retry?: number | false
109
- onRequest?(context: FetchContext): Promise<void> | void
110
- onRequestError?(
111
- context: FetchContext & {
112
- error: Error
113
- }
114
- ): Promise<void> | void
115
- onResponse?(
116
- context: FetchContext & {
117
- response: FetchResponse<R>
118
- }
119
- ): Promise<void> | void
120
- onResponseError?(
121
- context: FetchContext & {
122
- response: FetchResponse<R>
123
- }
124
- ): Promise<void> | void
96
+ immutableKey?: boolean
97
+ baseURL?: string
98
+ useHandler?: boolean
99
+ handler?: (params: Record<string, any>) => Record<string, any>
100
+ offline?: () => void
101
+ }
102
+ export interface Interceptors {
103
+ onRequest?: FetchOptions['onRequest']
104
+ onRequestError?: FetchOptions['onRequestError']
105
+ onResponse?: FetchOptions['onResponse']
106
+ onResponseError?: FetchOptions['onResponseError']
125
107
  }
126
108
  ```
127
109
 
128
- ### Type
129
-
130
- [type](https://nuxt.com/docs/api/composables/use-async-data#type)
131
-
132
- ## 使用方式
133
-
134
- ```bash
135
- pnpm add nuxt-custom-fetch
136
- ```
110
+ ## 示例
137
111
 
138
112
  ```ts
139
- // nuxt.config.ts
140
- export default defineNuxtConfig({
141
- modules: ['nuxt-custom-fetch']
142
- })
143
-
144
- // ajax.ts文件
145
- import type { FetchOptions } from 'ofetch'
146
- const ajax = new CustomFetch({
147
- baseURL: '',
148
- // 全局处理query\params的方法
149
- handler: (params = {}) => {
150
- params.aa = 111
151
- return params
152
- }
153
- })
154
-
113
+ // api.ts
155
114
  export const getInfo = (params: Record<string, any>) =>
156
- ajax.get<DataT>('/api/get-ip', { params }, options?: AsyncDataOptions<DataT>)
115
+ ajax.get<DataT>('/api/get-ip', { params }, {})
157
116
  ```
158
117
 
159
118
  ```ts
119
+ // index.vue
160
120
  import { getInfo } from './ajax'
161
-
162
121
  const { data, error, pending } = await getInfo({
163
122
  sign: 123
164
123
  })
package/dist/module.json CHANGED
@@ -1,5 +1,9 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "configKey": "customFetch",
4
- "version": "2.0.3"
4
+ "version": "2.1.0",
5
+ "builder": {
6
+ "@nuxt/module-builder": "0.7.0",
7
+ "unbuild": "unknown"
8
+ }
5
9
  }
package/dist/module.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { fileURLToPath } from 'url';
1
+ import { fileURLToPath } from 'node:url';
2
2
  import { defineNuxtModule, createResolver, addImports } from '@nuxt/kit';
3
3
 
4
4
  const module = defineNuxtModule({
@@ -1,14 +1,15 @@
1
1
  import type { NitroFetchRequest } from 'nitropack';
2
2
  import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
3
- import type { HTTPConfig, Interceptors, FetchMethod, KeysOf, PickFrom } from './type';
3
+ import type { FetchMethod, HTTPConfig, Interceptors, KeysOf, PickFrom } from './type.js';
4
4
  type CustomFetchReturnValue<DataT, ErrorT> = AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
5
+ declare function Noop(): void;
5
6
  export declare class CustomFetch {
6
- baseURL: any;
7
+ baseURL: string | undefined;
7
8
  immutableKey: boolean;
8
9
  params: HTTPConfig;
9
10
  baseHandler: HTTPConfig['handler'];
10
11
  interceptors: Interceptors;
11
- offline: () => void;
12
+ offline: typeof Noop;
12
13
  constructor(config?: HTTPConfig);
13
14
  private baseConfig;
14
15
  http<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config: HTTPConfig & {
@@ -1,12 +1,9 @@
1
1
  import { hash } from "ohash";
2
- import { createError, ref, toValue, unref, useAsyncData, useNuxtApp } from "#imports";
3
- const Noop = () => {
4
- };
2
+ import { createError, reactive, ref, toValue, unref, useAsyncData, useNuxtApp } from "#imports";
3
+ function Noop() {
4
+ }
5
5
  function generateOptionSegments(opts) {
6
- const segments = [
7
- toValue(opts.method)?.toUpperCase() || "GET",
8
- toValue(opts.baseURL)
9
- ];
6
+ const segments = [toValue(opts.method)?.toUpperCase() || "GET", toValue(opts.baseURL)];
10
7
  for (const _obj of [opts.params || opts.query]) {
11
8
  const obj = toValue(_obj);
12
9
  if (!obj) {
@@ -36,9 +33,7 @@ export class CustomFetch {
36
33
  interceptors = {};
37
34
  offline = Noop;
38
35
  constructor(config = { baseURL: "" }) {
39
- this.params = {
40
- ...config
41
- };
36
+ this.params = { ...config };
42
37
  this.baseURL = config.baseURL;
43
38
  this.immutableKey = config.immutableKey ?? false;
44
39
  if (config.handler) {
@@ -55,35 +50,33 @@ export class CustomFetch {
55
50
  baseConfig(config) {
56
51
  const { useHandler = true, handler, query = {}, params = {} } = config;
57
52
  const baseHandler = handler || this.baseHandler;
58
- const mergeObj = { ...params, ...query };
53
+ const _name = Object.keys(query).length ? "query" : "params";
54
+ const mergeObj = {
55
+ ...query,
56
+ ...params
57
+ };
59
58
  if (useHandler && baseHandler && typeof baseHandler === "function") {
60
- return baseHandler({ ...mergeObj });
59
+ return { [_name]: baseHandler(mergeObj) };
61
60
  }
62
- return { ...mergeObj };
61
+ return { [_name]: { ...mergeObj } };
63
62
  }
64
- http(url, config, options) {
63
+ http(url, config, options = {}) {
65
64
  config.baseURL = config?.baseURL || this.baseURL;
66
- config.query = this.baseConfig(config);
65
+ Object.assign(config, this.baseConfig(config));
66
+ const { onRequest, onRequestError, onResponse, onResponseError, offline, handler, useHandler, immutableKey, ...restAjaxConfig } = config;
67
67
  if (process.client && navigator && !navigator.onLine) {
68
- config.offline && config.offline();
68
+ if (offline) {
69
+ offline();
70
+ }
69
71
  }
70
72
  const interceptors = this.interceptors;
71
- const {
72
- onRequest,
73
- onRequestError,
74
- onResponse,
75
- onResponseError,
76
- offline,
77
- ...restAjaxConfig
78
- } = config;
73
+ const _config = reactive({ ...restAjaxConfig });
79
74
  const defaultOptions = {
80
75
  onRequest(ctx) {
81
- [interceptors.onRequest, onRequest].map((fn) => fn && fn(ctx));
76
+ [interceptors.onRequest, onRequest].forEach((fn) => fn?.(ctx));
82
77
  },
83
78
  onRequestError(ctx) {
84
- [interceptors.onRequestError, onRequestError].map(
85
- (fn) => fn && fn(ctx)
86
- );
79
+ [interceptors.onRequestError, onRequestError].forEach((fn) => fn?.(ctx));
87
80
  throw createError({
88
81
  statusCode: ctx.error.statusCode,
89
82
  statusMessage: ctx.error.message,
@@ -92,13 +85,15 @@ export class CustomFetch {
92
85
  });
93
86
  },
94
87
  onResponse(ctx) {
95
- interceptors.onResponse && interceptors.onResponse(ctx);
96
- onResponse && onResponse(ctx);
88
+ if (interceptors.onResponse) {
89
+ interceptors.onResponse(ctx);
90
+ }
91
+ if (onResponse) {
92
+ onResponse(ctx);
93
+ }
97
94
  },
98
95
  onResponseError(ctx) {
99
- [interceptors.onResponseError, onResponseError].map(
100
- (fn) => fn && fn(ctx)
101
- );
96
+ [interceptors.onResponseError, onResponseError].forEach((fn) => fn?.(ctx));
102
97
  throw createError({
103
98
  statusCode: ctx.response.status,
104
99
  statusMessage: ctx.request.toString(),
@@ -108,18 +103,19 @@ export class CustomFetch {
108
103
  }
109
104
  };
110
105
  const hashValue = ["custom|", url];
111
- if (!this.immutableKey) {
106
+ if (!this.immutableKey || !immutableKey) {
112
107
  hashValue.push(...generateOptionSegments(config));
113
108
  }
114
109
  const key = hash(hashValue);
115
- const handler = () => {
110
+ options.default = options.default ?? (() => null);
111
+ const _handler = () => {
116
112
  if (_cachedController.get(key)) {
117
113
  _cachedController.get(key)?.abort?.();
118
114
  }
119
115
  return $fetch(url, {
120
116
  signal: _cachedController.get(key)?.signal,
121
117
  ...defaultOptions,
122
- ...restAjaxConfig
118
+ ..._config
123
119
  });
124
120
  };
125
121
  const nuxtApp = useNuxtApp();
@@ -135,7 +131,7 @@ export class CustomFetch {
135
131
  asyncData.status.value = "pending";
136
132
  const promise = new Promise((resolve, reject) => {
137
133
  try {
138
- resolve(handler());
134
+ resolve(_handler());
139
135
  _cachedController.set(key, controller);
140
136
  } catch (err) {
141
137
  reject(err);
@@ -163,16 +159,18 @@ export class CustomFetch {
163
159
  });
164
160
  return promise;
165
161
  }
166
- return useAsyncData(config.key || key, handler, options);
162
+ return useAsyncData(config.key || key, _handler, options);
167
163
  }
168
164
  get(url, config = {}, options) {
169
- return this.http(url, { ...config, method: "GET" }, options);
165
+ return this.http(url, {
166
+ ...config,
167
+ method: "GET"
168
+ }, options);
170
169
  }
171
170
  post(url, config = {}, options) {
172
- return this.http(
173
- url,
174
- { ...config, method: "POST" },
175
- options
176
- );
171
+ return this.http(url, {
172
+ ...config,
173
+ method: "POST"
174
+ }, options);
177
175
  }
178
176
  }
@@ -1,6 +1,6 @@
1
- import type { FetchRequest, FetchOptions, FetchError, FetchResponse } from 'ofetch';
2
- export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, K[number]> : T;
3
- export type KeysOf<T> = Array<T extends T ? keyof T extends string ? keyof T : never : never>;
1
+ import type { FetchError, FetchOptions, FetchRequest, FetchResponse } from 'ofetch';
2
+ export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? (keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, K[number]>) : T;
3
+ export type KeysOf<T> = Array<T extends T ? (keyof T extends string ? keyof T : never) : never>;
4
4
  export interface OnRequestType {
5
5
  request: FetchRequest;
6
6
  options: FetchOptions;
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
- "version": "2.0.3",
4
- "license": "MIT",
5
3
  "type": "module",
4
+ "version": "2.1.0",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/xjccc/nuxt-custom-fetch.git"
9
+ },
6
10
  "exports": {
7
11
  ".": {
8
12
  "import": "./dist/module.mjs",
@@ -14,25 +18,49 @@
14
18
  "files": [
15
19
  "dist"
16
20
  ],
17
- "repository": {
18
- "type": "git",
19
- "url": "https://github.com/xjccc/nuxt-custom-fetch.git"
20
- },
21
21
  "scripts": {
22
22
  "prepack": "nuxt-module-build build",
23
23
  "dev": "nuxi dev playground",
24
24
  "dev:build": "nuxi build playground",
25
- "dev:prepare": "nuxt-module-build --stub && nuxi prepare playground"
25
+ "dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
26
+ "echo:husky": "echo 'npx lint-staged' > .husky/pre-commit && echo 'npx --no-install commitlint --edit \"$1\"' > .husky/commit-msg",
27
+ "lint": "eslint .",
28
+ "lint:fix": "eslint . --fix",
29
+ "prepare": "husky",
30
+ "commit": "git-cz",
31
+ "release": "changelogen --release && pnpm prepack && npm publish && git push --follow-tags"
32
+ },
33
+ "config": {
34
+ "commitizen": {
35
+ "path": "node_modules/cz-git"
36
+ }
26
37
  },
27
38
  "dependencies": {
28
- "@nuxt/kit": "^3.11.1",
29
- "typescript": "^5.4.2"
39
+ "@nuxt/kit": "^3.11.2",
40
+ "ohash": "^1.1.3",
41
+ "typescript": "^5.4.5"
30
42
  },
31
43
  "devDependencies": {
32
- "@nuxt/module-builder": "^0.5.5",
33
- "@nuxt/schema": "^3.11.1",
34
- "@nuxtjs/eslint-config-typescript": "^12.1.0",
35
- "eslint": "^8.57.0",
36
- "nuxt": "^3.11.1"
44
+ "@antfu/eslint-config": "^2.18.1",
45
+ "@commitlint/cli": "^19.3.0",
46
+ "@commitlint/config-conventional": "^19.2.2",
47
+ "@nuxt/module-builder": "^0.7.0",
48
+ "@nuxt/schema": "^3.11.2",
49
+ "@types/node": "^20.12.12",
50
+ "changelogen": "^0.5.5",
51
+ "commitizen": "^4.3.0",
52
+ "cz-git": "^1.9.1",
53
+ "eslint": "^9.3.0",
54
+ "husky": "^9.0.11",
55
+ "lint-staged": "^15.2.5",
56
+ "nuxt": "^3.11.2"
57
+ },
58
+ "husky": {
59
+ "hooks": {
60
+ "pre-commit": "lint-staged"
61
+ }
62
+ },
63
+ "lint-staged": {
64
+ "*": "eslint . --fix"
37
65
  }
38
66
  }
File without changes