nuxt-custom-fetch 4.0.0-alpha.1 → 4.0.0-alpha.11

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,7 +2,12 @@
2
2
 
3
3
  simple wrapper useAsyncData
4
4
 
5
- `version >= 3.17.0`
5
+ `v4`: `version >= 3.17.0`
6
+ `v2`: `version >= 3.0.0 < 3.17.0`
7
+
8
+ ## Break Change
9
+
10
+ 1. `http` method is removed, use `request` instead
6
11
 
7
12
  ## Attention
8
13
 
@@ -36,13 +41,13 @@ const ajax = new CustomFetch({
36
41
  baseURL: ''
37
42
  })
38
43
 
39
- // `http|get|post`
44
+ // `request|get|post`
40
45
  ajax.get('/api/user')
41
46
 
42
47
  ajax.post('/api/user')
43
48
 
44
- ajax.http({
45
- method: 'GET'
49
+ ajax.request({
50
+ method: 'DELETE'
46
51
  })
47
52
  ```
48
53
 
@@ -59,7 +64,7 @@ export declare class CustomFetch {
59
64
  offline: typeof Noop
60
65
  showLogs: boolean
61
66
  constructor (config: CustomFetchOptions)
62
- http<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
67
+ request<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
63
68
  method: FetchMethod
64
69
  }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
65
70
  get<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
@@ -13,7 +13,7 @@ export declare class CustomFetch {
13
13
  showLogs: boolean;
14
14
  constructor(config: CustomFetchOptions);
15
15
  private baseConfig;
16
- http<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
16
+ request<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
17
17
  method: FetchMethod;
18
18
  }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>;
19
19
  get<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>;
@@ -1,5 +1,5 @@
1
1
  import { asyncDataDefaults, pendingWhenIdle } from "#build/nuxt.config.mjs";
2
- import { clearNuxtData, createError, getCurrentScope, onScopeDispose, reactive, ref, shallowRef, unref, useAsyncData, useRequestFetch, useRuntimeConfig, watch } from "#imports";
2
+ import { clearNuxtData, computed, createError, getCurrentScope, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
3
3
  import { hash, serialize } from "ohash";
4
4
  import { generateOptionSegments, Noop, pick } from "./utils.js";
5
5
  const _cachedController = /* @__PURE__ */ new Map();
@@ -43,7 +43,7 @@ export class CustomFetch {
43
43
  }
44
44
  return { [_name]: { ...mergeObj } };
45
45
  }
46
- http(url, config, options = {}) {
46
+ request(url, config, options = {}) {
47
47
  const app = useRuntimeConfig().app;
48
48
  config.baseURL ??= this.baseURL || app.baseURL;
49
49
  Object.assign(config, this.baseConfig(config));
@@ -55,7 +55,7 @@ export class CustomFetch {
55
55
  } catch (error) {
56
56
  console.warn("[Custom Fetch] couldn't serialize `Body:`", error);
57
57
  }
58
- console.warn("[Custom Fetch] `Request:`", url, " `Query:`", serialize(generateOptionSegmentsWithConfig), " `Body:`", bodyLogs);
58
+ console.warn("[Custom Fetch] `Request:`", url, "`Query:`", serialize(generateOptionSegmentsWithConfig), " `Body:`", bodyLogs);
59
59
  }
60
60
  const { onRequest, onRequestError, onResponse, onResponseError, offline, handler, useHandler, showLogs, immutableKey, ...asyncDataOptions } = config;
61
61
  if (import.meta.client && navigator && !navigator.onLine) {
@@ -113,7 +113,6 @@ export class CustomFetch {
113
113
  });
114
114
  }
115
115
  };
116
- let key = config.key;
117
116
  const hashValue = ["custom_fetch:", url];
118
117
  if (import.meta.dev && !config.key && (this.immutableKey || immutableKey)) {
119
118
  console.warn("[Custom Fetch] immutableKey is enabled, the key will be generated by hash([custom_fetch:, url])");
@@ -121,26 +120,45 @@ export class CustomFetch {
121
120
  if (!this.immutableKey && !immutableKey) {
122
121
  hashValue.push(...generateOptionSegmentsWithConfig);
123
122
  }
124
- key ??= hash(hashValue).replace(/[-_]/g, "").slice(0, 10);
123
+ const hashKey = hash(hashValue).replace(/[-_]/g, "").slice(0, 10);
124
+ const key = computed(() => toValue(config.key) || hashKey);
125
+ watch(key, (key2, oldKey) => {
126
+ if (oldKey) {
127
+ _cachedController.get(oldKey)?.abort?.();
128
+ _cachedController.delete(oldKey);
129
+ } else {
130
+ const controller2 = typeof AbortController !== "undefined" ? new AbortController() : {};
131
+ _cachedController.set(key2, controller2);
132
+ }
133
+ });
125
134
  const _handler = () => {
126
- if (_cachedController.get(key)) {
127
- _cachedController.get(key)?.abort?.();
135
+ if (_cachedController.get(key.value)) {
136
+ _cachedController.get(key.value)?.abort?.();
128
137
  }
129
138
  return useRequestFetch()(url, {
130
- signal: _cachedController.get(key)?.signal,
139
+ signal: _cachedController.get(key.value)?.signal,
131
140
  ...defaultOptions,
132
141
  ..._config
133
142
  });
134
143
  };
135
144
  const controller = typeof AbortController !== "undefined" ? new AbortController() : {};
136
- if (import.meta.client) {
145
+ const nuxtApp = useNuxtApp();
146
+ if (import.meta.client && !nuxtApp.isHydrating) {
147
+ if (nuxtApp._asyncData[key.value]?._deps) {
148
+ nuxtApp._asyncData[key.value].execute({
149
+ cause: "initial",
150
+ dedupe: options.dedupe
151
+ });
152
+ return nuxtApp._asyncData[key.value];
153
+ }
137
154
  const _ref = options.deep ? ref : shallowRef;
155
+ options.default ??= () => asyncDataDefaults.value;
138
156
  const asyncData = {
139
157
  data: _ref(null),
140
158
  error: _ref(null),
141
159
  status: _ref("idle"),
142
160
  pending: _ref(false),
143
- clear: () => clearNuxtData(key)
161
+ clear: () => clearNuxtData(key.value)
144
162
  };
145
163
  if (pendingWhenIdle) {
146
164
  asyncData.pending.value = true;
@@ -149,7 +167,7 @@ export class CustomFetch {
149
167
  const promise = new Promise((resolve, reject) => {
150
168
  try {
151
169
  resolve(_handler());
152
- _cachedController.set(key, controller);
170
+ _cachedController.set(key.value, controller);
153
171
  } catch (err) {
154
172
  reject(err);
155
173
  }
@@ -167,14 +185,14 @@ export class CustomFetch {
167
185
  return asyncData;
168
186
  }).catch((error) => {
169
187
  asyncData.error.value = createError(error);
170
- asyncData.data.value = unref(options?.default());
188
+ asyncData.data.value = unref(options.default());
171
189
  asyncData.status.value = "error";
172
190
  return asyncData;
173
191
  }).finally(() => {
174
192
  if (pendingWhenIdle) {
175
193
  asyncData.pending.value = false;
176
194
  }
177
- _cachedController.delete(key);
195
+ _cachedController.delete(key.value);
178
196
  });
179
197
  asyncData.refresh = asyncData.execute = () => _handler().then((result) => asyncData.data.value = result);
180
198
  const hasScope = getCurrentScope();
@@ -191,13 +209,13 @@ export class CustomFetch {
191
209
  return useAsyncData(key, _handler, options);
192
210
  }
193
211
  get(url, config = {}, options) {
194
- return this.http(url, {
212
+ return this.request(url, {
195
213
  ...config,
196
214
  method: "GET"
197
215
  }, options);
198
216
  }
199
217
  post(url, config = {}, options) {
200
- return this.http(url, {
218
+ return this.request(url, {
201
219
  ...config,
202
220
  method: "POST"
203
221
  }, options);
@@ -1,12 +1,13 @@
1
+ import type { MaybeRefOrGetter } from '#imports';
1
2
  import type { FetchOptions } from 'ofetch';
2
3
  export type { FetchContext, FetchResponse } from 'ofetch';
3
4
  /** https://github.com/nuxt/nuxt/blob/edeb0759a455dbafd030f0b5ae1d5a39ad0dfc2a/packages/nuxt/src/app/composables/asyncData.ts#L20 */
4
- 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;
5
- export type KeysOf<T> = Array<T extends T ? (keyof T extends string ? keyof T : never) : never>;
5
+ 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;
6
+ export type KeysOf<T> = Array<T extends T ? keyof T extends string ? keyof T : never : never>;
6
7
  export type FetchMethod = 'options' | 'GET' | 'POST' | 'get' | 'HEAD' | 'PATCH' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'post' | 'head' | 'patch' | 'put' | 'delete' | 'connect' | 'trace' | undefined;
7
8
  export interface CustomFetchOptions extends Omit<FetchOptions, 'method'> {
8
9
  /** unique key for fetch */
9
- key?: string;
10
+ key?: MaybeRefOrGetter<string>;
10
11
  /** hash key for fetch, with [customFetch: + url] without query */
11
12
  immutableKey?: boolean;
12
13
  /** show logs */
@@ -1,6 +1,6 @@
1
1
  import type { CustomFetchOptions, FetchMethod } from './type.js';
2
2
  export declare function Noop(): void;
3
- export declare function generateOptionSegments(opts: CustomFetchOptions & {
3
+ export declare function generateOptionSegments<_ResT>(opts: CustomFetchOptions & {
4
4
  method: FetchMethod;
5
5
  }): (string | Record<string, string> | undefined)[];
6
6
  export declare function pick(obj: Record<string, any>, keys: string[]): any;
@@ -1,9 +1,13 @@
1
- import { toValue } from "#imports";
1
+ import { reactive, toValue } from "#imports";
2
+ import { isPlainObject } from "@vue/shared";
2
3
  import { hash } from "ohash";
3
4
  export function Noop() {
4
5
  }
5
6
  export function generateOptionSegments(opts) {
6
- const segments = [toValue(opts.method)?.toUpperCase() || "GET", toValue(opts.baseURL)];
7
+ const segments = [
8
+ toValue(opts.method)?.toUpperCase() || "GET",
9
+ toValue(opts.baseURL)
10
+ ];
7
11
  for (const _obj of [opts.params || opts.query]) {
8
12
  const obj = toValue(_obj);
9
13
  if (!obj) {
@@ -16,7 +20,27 @@ export function generateOptionSegments(opts) {
16
20
  segments.push(unwrapped);
17
21
  }
18
22
  if (opts.body) {
19
- segments.push(hash(toValue(opts.body)));
23
+ const value = toValue(opts.body);
24
+ if (!value) {
25
+ segments.push(hash(value));
26
+ } else if (value instanceof ArrayBuffer) {
27
+ segments.push(hash(Object.fromEntries([...new Uint8Array(value).entries()].map(([k, v]) => [k, v.toString()]))));
28
+ } else if (value instanceof FormData) {
29
+ const obj = {};
30
+ for (const entry of value.entries()) {
31
+ const [key, val] = entry;
32
+ obj[key] = val instanceof File ? val.name : val;
33
+ }
34
+ segments.push(hash(obj));
35
+ } else if (isPlainObject(value)) {
36
+ segments.push(hash(reactive(value)));
37
+ } else {
38
+ try {
39
+ segments.push(hash(value));
40
+ } catch {
41
+ console.warn("[Custom Fetch] Failed to hash body", value);
42
+ }
43
+ }
20
44
  }
21
45
  return segments;
22
46
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "type": "module",
4
- "version": "4.0.0-alpha.1",
4
+ "version": "4.0.0-alpha.11",
5
5
  "packageManager": "pnpm@8.15.3+sha1.64838798f519c18029c1e8a1310e16101fc2eda0",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -37,24 +37,26 @@
37
37
  }
38
38
  },
39
39
  "dependencies": {
40
- "ohash": "^2.0.11"
40
+ "@vue/shared": "^3.5.16",
41
+ "ohash": "^2.0.11",
42
+ "vue": "^3.5.16"
41
43
  },
42
44
  "devDependencies": {
43
- "@antfu/eslint-config": "^4.12.0",
44
- "@commitlint/cli": "^19.8.0",
45
- "@commitlint/config-conventional": "^19.8.0",
46
- "@nuxt/kit": "npm:@nuxt/kit-nightly@4.0.0-29086370.088bcd45",
45
+ "@antfu/eslint-config": "^4.13.3",
46
+ "@commitlint/cli": "^19.8.1",
47
+ "@commitlint/config-conventional": "^19.8.1",
48
+ "@nuxt/kit": "3.17.5",
47
49
  "@nuxt/module-builder": "^1.0.1",
48
- "@nuxt/schema": "npm:@nuxt/schema-nightly@4.0.0-29086370.088bcd45",
49
- "@types/node": "^22.14.1",
50
+ "@nuxt/schema": "3.17.5",
51
+ "@types/node": "^22.15.29",
50
52
  "changelogen": "^0.6.1",
51
53
  "commitizen": "^4.3.1",
52
54
  "cz-git": "^1.11.1",
53
- "eslint": "^9.24.0",
55
+ "eslint": "^9.28.0",
54
56
  "husky": "^9.1.7",
55
- "lint-staged": "^15.5.1",
56
- "nitro": "npm:nitro-nightly@latest",
57
- "nuxt": "npm:nuxt-nightly@4.0.0-29086370.088bcd45",
57
+ "lint-staged": "^16.1.0",
58
+ "nitro": "npm:nitropack@^2.11.12",
59
+ "nuxt": "3.17.5",
58
60
  "typescript": "5.8.3"
59
61
  },
60
62
  "husky": {