nuxt-custom-fetch 1.1.6 → 2.0.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,19 @@
2
2
 
3
3
  简单封装 useAsyncData
4
4
 
5
+ ## 注意
6
+
7
+ 请求的使用形式,类似于之前的`ajax`,修改参数后,重新调用封装方法。
8
+
9
+ 1. 在 onMounted 中请求无效(version > 3.0.0)
10
+
11
+ - 在下一个 nextTick 中执行,或者设置{server: false},watch pending 变化
12
+
13
+ 2. 因为封装后,参数的`响应式丢失`,导致`watch`无法使用
14
+
15
+ 3. `refresh`和`execute`使用上也需要注意,参数不是响应式的,所以会一直是第一次请求的参数
16
+
17
+
5
18
  ## HTTPOptions
6
19
 
7
20
  实例化全局 CustomFetch
@@ -9,7 +22,7 @@
9
22
  ```ts
10
23
  {
11
24
  baseURL?: string
12
- paramsHandler?: (params: Record<string, any>) => Record<string, any>
25
+ handler?: (params: Record<string, any>) => Record<string, any>
13
26
  offline?: () => void
14
27
  }
15
28
  ```
@@ -18,9 +31,17 @@
18
31
 
19
32
  当前实例下的 baseURL
20
33
 
21
- ### paramsHandler
34
+ ### handler
22
35
 
23
- 处理 params 的自定义函数
36
+ 处理 query & params 的自定义函数
37
+
38
+ ```ts
39
+ {
40
+ handler({...query, ...params}) {
41
+ return {}
42
+ }
43
+ }
44
+ ```
24
45
 
25
46
  ### 请求-响应拦截
26
47
 
@@ -64,11 +85,6 @@
64
85
 
65
86
  `http|get|post`
66
87
 
67
- ```js
68
- import { hash } from 'ohash'
69
- const key = hash(JSON.stringify(restConfig) + url)
70
- ```
71
-
72
88
  ### offline
73
89
 
74
90
  客户端中,离线时调用(判断 navigator.onLine)
@@ -82,8 +98,8 @@ interface fetchOptions {
82
98
  baseURL?: string
83
99
  key?: string
84
100
  body?: RequestInit['body'] | Record<string, any>
85
- useParamsHandler: HTTPConfig['paramsHandler']
86
- paramsHandler: HTTPConfig['paramsHandler']
101
+ useHandler: HTTPConfig['useHandler']
102
+ handler: HTTPConfig['handler']
87
103
  params?: SearchParameters
88
104
  query?: SearchParameters
89
105
  parseResponse?: (responseText: string) => any
@@ -130,7 +146,7 @@ import type { FetchOptions } from 'ofetch'
130
146
  const ajax = new CustomFetch({
131
147
  baseURL: '',
132
148
  // 全局处理query\params的方法
133
- paramsHandler: (params = {}) => {
149
+ handler: (params = {}) => {
134
150
  params.aa = 111
135
151
  return params
136
152
  }
@@ -149,12 +165,6 @@ const { data, error, pending } = await getInfo({
149
165
  console.log(data.value)
150
166
  ```
151
167
 
152
- ## 注意
153
-
154
- 在 onMounted 中请求无效(version > 3.0.0)
155
-
156
- - 在下一个 nextTick 中执行,或者设置{server: false},watch pending 变化
157
-
158
168
  ## Development
159
169
 
160
170
  - Run `npm run dev:prepare` to generate type stubs.
package/dist/module.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "configKey": "customFetch",
4
- "version": "1.1.6"
4
+ "version": "2.0.0"
5
5
  }
@@ -1,21 +1,19 @@
1
+ import type { NitroFetchRequest } from 'nitropack';
1
2
  import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
2
- import type { HTTPConfig, Interceptors, AjaxConfig, KeysOf, PickFrom } from './type';
3
- export declare const ajax: <DataT, ErrorT = Error | null>(url: string, key: string, config: AjaxConfig, options?: AsyncDataOptions<DataT>) => AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
3
+ import type { HTTPConfig, Interceptors, FetchMethod, KeysOf, PickFrom } from './type';
4
+ type CustomFetchReturnValue<DataT, ErrorT> = AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
4
5
  export declare class CustomFetch {
5
6
  baseURL: any;
6
7
  params: HTTPConfig;
7
- baseParamsHandler: HTTPConfig['paramsHandler'];
8
+ baseHandler: HTTPConfig['handler'];
8
9
  interceptors: Interceptors;
9
10
  offline: () => void;
10
11
  constructor(config?: HTTPConfig);
11
12
  private baseConfig;
12
- http<DataT, ErrorT = Error | null>(url: string, config?: HTTPConfig & {
13
- key?: string;
14
- }, options?: AsyncDataOptions<DataT>): AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
15
- get<DataT, ErrorT = Error | null>(url: string, config?: HTTPConfig & {
16
- key?: string;
17
- }, options?: AsyncDataOptions<DataT>): AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
18
- post<DataT, ErrorT = Error | null>(url: string, config?: HTTPConfig & {
19
- key?: string;
20
- }, options?: AsyncDataOptions<DataT>): AsyncData<PickFrom<DataT, KeysOf<DataT>> | null, (ErrorT extends Error | NuxtError<unknown> ? ErrorT : NuxtError<ErrorT>) | null>;
13
+ http<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config: HTTPConfig & {
14
+ method: FetchMethod;
15
+ }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>;
16
+ get<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config?: HTTPConfig, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>;
17
+ post<DataT, ErrorT = Error | null>(url: NitroFetchRequest, config?: HTTPConfig, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, ErrorT>;
21
18
  }
19
+ export {};
@@ -1,56 +1,6 @@
1
1
  import { hash } from "ohash";
2
- import { createError } from "h3";
3
- import { toValue, useAsyncData } from "#imports";
4
- export const ajax = (url, key, config, options) => {
5
- if (process.client && navigator && !navigator.onLine) {
6
- config.offline && config.offline();
7
- }
8
- const {
9
- onRequest,
10
- onRequestError,
11
- onResponse,
12
- onResponseError,
13
- interceptors,
14
- ...restAjaxConfig
15
- } = config;
16
- const defaultOptions = {
17
- onRequest(ctx) {
18
- [interceptors.onRequest, onRequest].map((fn) => fn && fn(ctx));
19
- },
20
- onRequestError(ctx) {
21
- [interceptors.onRequestError, onRequestError].map((fn) => fn && fn(ctx));
22
- throw createError({
23
- statusCode: ctx.error.statusCode,
24
- statusMessage: ctx.error.message,
25
- message: ctx.error.message,
26
- fatal: true
27
- });
28
- },
29
- onResponse(ctx) {
30
- interceptors.onResponse && interceptors.onResponse(ctx);
31
- onResponse && onResponse(ctx);
32
- },
33
- onResponseError(ctx) {
34
- [interceptors.onResponseError, onResponseError].map(
35
- (fn) => fn && fn(ctx)
36
- );
37
- throw createError({
38
- statusCode: ctx.response.status,
39
- statusMessage: ctx.request.toString(),
40
- message: ctx.response._data,
41
- fatal: true
42
- });
43
- }
44
- };
45
- return useAsyncData(
46
- key,
47
- () => $fetch(url, {
48
- ...defaultOptions,
49
- ...restAjaxConfig,
50
- method: restAjaxConfig.method
51
- }),
52
- options
53
- );
2
+ import { createError, ref, toValue, unref, useAsyncData, useNuxtApp } from "#imports";
3
+ const Noop = () => {
54
4
  };
55
5
  function generateOptionSegments(opts) {
56
6
  const segments = [
@@ -70,12 +20,18 @@ function generateOptionSegments(opts) {
70
20
  }
71
21
  return segments;
72
22
  }
73
- const Noop = () => {
74
- };
23
+ function pick(obj, keys) {
24
+ const newObj = {};
25
+ for (const key of keys) {
26
+ newObj[key] = obj[key];
27
+ }
28
+ return newObj;
29
+ }
30
+ const _cachedController = /* @__PURE__ */ new Map();
75
31
  export class CustomFetch {
76
32
  baseURL;
77
33
  params = {};
78
- baseParamsHandler;
34
+ baseHandler;
79
35
  interceptors = {};
80
36
  offline = Noop;
81
37
  constructor(config = { baseURL: "" }) {
@@ -83,8 +39,8 @@ export class CustomFetch {
83
39
  ...config
84
40
  };
85
41
  this.baseURL = config.baseURL;
86
- if (config.paramsHandler) {
87
- this.baseParamsHandler = config.paramsHandler;
42
+ if (config.handler) {
43
+ this.baseHandler = config.handler;
88
44
  }
89
45
  this.offline = config?.offline || Noop;
90
46
  this.interceptors = {
@@ -95,33 +51,116 @@ export class CustomFetch {
95
51
  };
96
52
  }
97
53
  baseConfig(config) {
98
- const { useParamsHandler = true, paramsHandler } = config;
99
- const handler = paramsHandler || this.baseParamsHandler;
100
- const params = (config.query ? config.query : config.params) || {};
101
- if (useParamsHandler && handler && typeof handler === "function") {
102
- delete config.params;
103
- delete config.query;
104
- return handler({ ...params });
54
+ const { useHandler = true, handler, query = {}, params = {} } = config;
55
+ const baseHandler = handler || this.baseHandler;
56
+ const mergeObj = { ...params, ...query };
57
+ if (useHandler && baseHandler && typeof baseHandler === "function") {
58
+ return baseHandler({ ...mergeObj });
105
59
  }
106
- return { ...params };
60
+ return { ...mergeObj };
107
61
  }
108
- http(url, config = {}, options) {
109
- const key = config.key ? config.key : hash([url, ...generateOptionSegments(config)]);
110
- const baseURL = config?.baseURL || this.baseURL;
111
- const query = this.baseConfig(config);
112
- const offline = config?.offline || this.offline;
113
- return ajax(
114
- url,
115
- key,
116
- {
117
- baseURL,
118
- ...config,
119
- query,
120
- interceptors: this.interceptors,
121
- offline
62
+ http(url, config, options) {
63
+ config.baseURL = config?.baseURL || this.baseURL;
64
+ config.query = this.baseConfig(config);
65
+ if (process.client && navigator && !navigator.onLine) {
66
+ config.offline && config.offline();
67
+ }
68
+ const interceptors = this.interceptors;
69
+ const {
70
+ onRequest,
71
+ onRequestError,
72
+ onResponse,
73
+ onResponseError,
74
+ offline,
75
+ ...restAjaxConfig
76
+ } = config;
77
+ const defaultOptions = {
78
+ onRequest(ctx) {
79
+ [interceptors.onRequest, onRequest].map((fn) => fn && fn(ctx));
122
80
  },
123
- options
124
- );
81
+ onRequestError(ctx) {
82
+ [interceptors.onRequestError, onRequestError].map(
83
+ (fn) => fn && fn(ctx)
84
+ );
85
+ throw createError({
86
+ statusCode: ctx.error.statusCode,
87
+ statusMessage: ctx.error.message,
88
+ message: ctx.error.message,
89
+ fatal: true
90
+ });
91
+ },
92
+ onResponse(ctx) {
93
+ interceptors.onResponse && interceptors.onResponse(ctx);
94
+ onResponse && onResponse(ctx);
95
+ },
96
+ onResponseError(ctx) {
97
+ [interceptors.onResponseError, onResponseError].map(
98
+ (fn) => fn && fn(ctx)
99
+ );
100
+ throw createError({
101
+ statusCode: ctx.response.status,
102
+ statusMessage: ctx.request.toString(),
103
+ message: ctx.response._data,
104
+ fatal: true
105
+ });
106
+ }
107
+ };
108
+ const key = hash(["custom|", url, ...generateOptionSegments(config)]);
109
+ const handler = () => {
110
+ if (_cachedController.get(key)) {
111
+ _cachedController.get(key)?.abort?.();
112
+ }
113
+ return $fetch(url, {
114
+ signal: _cachedController.get(key)?.signal,
115
+ ...defaultOptions,
116
+ ...restAjaxConfig
117
+ });
118
+ };
119
+ const nuxtApp = useNuxtApp();
120
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : {};
121
+ if (import.meta.client && !nuxtApp.isHydrating) {
122
+ const asyncData = {
123
+ data: ref(null),
124
+ pending: ref(true),
125
+ error: ref(null),
126
+ status: ref("idle")
127
+ };
128
+ asyncData.pending.value = true;
129
+ asyncData.status.value = "pending";
130
+ const promise = new Promise((resolve, reject) => {
131
+ try {
132
+ resolve(handler());
133
+ _cachedController.set(key, controller);
134
+ } catch (err) {
135
+ reject(err);
136
+ }
137
+ }).then(async (_result) => {
138
+ let result = _result;
139
+ if (options?.transform) {
140
+ result = await options.transform(_result);
141
+ }
142
+ if (options?.pick) {
143
+ result = pick(result, options.pick);
144
+ }
145
+ asyncData.data.value = result;
146
+ asyncData.error.value = null;
147
+ asyncData.status.value = "success";
148
+ return asyncData;
149
+ }).catch((error) => {
150
+ asyncData.error.value = createError(error);
151
+ asyncData.data.value = unref(options?.default());
152
+ asyncData.status.value = "error";
153
+ return asyncData;
154
+ }).finally(() => {
155
+ asyncData.pending.value = false;
156
+ _cachedController.delete(key);
157
+ });
158
+ return promise;
159
+ }
160
+ if (!config.key) {
161
+ return useAsyncData(handler, options);
162
+ }
163
+ return useAsyncData(config.key, handler, options);
125
164
  }
126
165
  get(url, config = {}, options) {
127
166
  return this.http(url, { ...config, method: "GET" }, options);
@@ -22,11 +22,11 @@ export interface OnResponseErrorType {
22
22
  }
23
23
  export type FetchMethod = 'options' | 'GET' | 'POST' | 'get' | 'HEAD' | 'PATCH' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'post' | 'head' | 'patch' | 'put' | 'delete' | 'connect' | 'trace' | undefined;
24
24
  export interface HTTPConfig extends Omit<FetchOptions, 'method'> {
25
+ key?: string;
25
26
  baseURL?: string;
26
- useParamsHandler?: boolean;
27
- paramsHandler?: (params: Record<string, any>) => Record<string, any>;
27
+ useHandler?: boolean;
28
+ handler?: (params: Record<string, any>) => Record<string, any>;
28
29
  offline?: () => void;
29
- method?: FetchMethod;
30
30
  }
31
31
  export interface Interceptors {
32
32
  onRequest?: FetchOptions['onRequest'];
@@ -34,9 +34,3 @@ export interface Interceptors {
34
34
  onResponse?: FetchOptions['onResponse'];
35
35
  onResponseError?: FetchOptions['onResponseError'];
36
36
  }
37
- export type AjaxConfig = FetchOptions & {
38
- key?: string;
39
- extraParams?: string[];
40
- offline?: () => void;
41
- interceptors: Interceptors;
42
- };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
- "version": "1.1.6",
3
+ "version": "2.0.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -19,7 +19,7 @@
19
19
  "url": "https://github.com/xjccc/nuxt-custom-fetch.git"
20
20
  },
21
21
  "scripts": {
22
- "prepack": "nuxt-module-build",
22
+ "prepack": "nuxt-module-build build",
23
23
  "dev": "nuxi dev playground",
24
24
  "dev:build": "nuxi build playground",
25
25
  "dev:prepare": "nuxt-module-build --stub && nuxi prepare playground"