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

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
@@ -1,62 +1,183 @@
1
- # Nuxt Module
1
+ # Nuxt Custom Fetch
2
2
 
3
- simple wrapper useAsyncData
3
+ A simple wrapper around Nuxt's `useAsyncData` to provide enhanced fetching capabilities with interceptors, request/response handling, and more.
4
4
 
5
- `v4`: `version >= 3.17.0`
6
- `v2`: `version >= 3.0.0 < 3.17.0`
5
+ ## Version Compatibility
7
6
 
8
- ## Break Change
7
+ - `v4`: Compatible with Nuxt v3.17.0 or higher
8
+ - `v2`: Compatible with Nuxt v3.0.0 to v3.16.x
9
9
 
10
- 1. `http` method is removed, use `request` instead
10
+ ## Breaking Changes in v4
11
11
 
12
- ## Attention
12
+ 1. `http` method has been removed, use `request` instead
13
13
 
14
- 1. Invalid request in onMounted
14
+ ## Key Features
15
15
 
16
- - Execute in `nextTick`, or set `{server: false}` to watch `status` changes
16
+ - Request lifecycle interceptors
17
+ - Automatic hash-based key generation
18
+ - Request parameter/query handling
19
+ - Response transformation
20
+ - Offline detection and handling
21
+ - Debug logs for requests
22
+ - Reactive fetching with `watch` support
23
+ - Request cancellation with abort controller
17
24
 
18
- 2. When using `refresh` and `execute`, it should also be noted that the parameters are not responsive, so they will always be the parameters requested for the first time
19
-
20
- 3. If a reactive object is passed and using `watch`, it will automatically re request
21
-
22
- ## Install
25
+ ## Installation
23
26
 
24
27
  ```bash
28
+ npm install nuxt-custom-fetch
29
+ # or
30
+ yarn add nuxt-custom-fetch
31
+ # or
25
32
  pnpm add nuxt-custom-fetch
26
33
  ```
27
34
 
35
+ Then add the module to your `nuxt.config.ts`:
36
+
28
37
  ```ts
29
- // nuxt.config.ts
30
38
  export default defineNuxtConfig({
31
39
  modules: ['nuxt-custom-fetch']
32
40
  })
33
41
  ```
34
42
 
35
- ## Usage
43
+ ## Basic Usage
36
44
 
37
- global CustomFetch
45
+ Create a global CustomFetch instance:
38
46
 
39
47
  ```ts
40
48
  const ajax = new CustomFetch({
41
- baseURL: ''
49
+ baseURL: 'https://api.example.com',
50
+ // Optional configurations
51
+ showLogs: true, // Show request logs in development
52
+ immutableKey: false, // Enable to use only URL for generating cache keys
53
+ // Optional request handler
54
+ handler: (params) => {
55
+ // Transform params/query before sending
56
+ return params
57
+ },
58
+ // Optional offline handler
59
+ offline: () => {
60
+ // Handle offline status
61
+ console.log('Device is offline')
62
+ }
42
63
  })
43
64
 
44
- // `request|get|post`
45
- ajax.get('/api/user')
65
+ // Available methods
66
+ ajax.get('/api/users')
67
+ ajax.post('/api/users', { body: { name: 'John' } })
68
+ ajax.request('/api/users', { method: 'DELETE' })
69
+ ```
70
+
71
+ ## Important Notes
72
+
73
+ ### Handling Requests in Client Components
74
+
75
+ 1. When using in client components, execute in `nextTick`, or set `{server: false}` to properly handle status changes.
76
+
77
+ 2. When using `refresh` and `execute` methods, note that parameters are not reactive, so they will always use the parameters from the first request.
78
+
79
+ 3. If you pass a reactive object with `watch` enabled, it will automatically trigger new requests when the watched values change.
80
+
81
+ ### Caching and Keys
82
+
83
+ The module generates hash-based keys for caching responses. You can:
84
+ - Provide your own `key` for precise cache control
85
+ - Enable `immutableKey` to use only the URL for generating cache keys (ignoring params/query)
86
+
87
+ ## Configuration Options
46
88
 
47
- ajax.post('/api/user')
89
+ ### CustomFetch Constructor Options
48
90
 
49
- ajax.request({
50
- method: 'DELETE'
91
+ ```typescript
92
+ // Create a new instance with configuration
93
+ const ajax = new CustomFetch({
94
+ baseURL: '', // Base URL for all requests
95
+ immutableKey: false, // If true, only use URL for key generation (default: false)
96
+ showLogs: true, // Show request logs (default: false in prod, true in dev)
97
+
98
+ // Request handling
99
+ useHandler: true, // Whether to use the handler function (default: true)
100
+ handler: undefined, // Transform params/query before sending
101
+
102
+ // Interceptors
103
+ onRequest: undefined, // Before request is sent
104
+ onRequestError: undefined, // When request error occurs
105
+ onResponse: undefined, // After response is received
106
+ onResponseError: undefined, // When response error occurs
107
+
108
+ // Offline handling
109
+ offline: undefined // Called when device is offline
110
+ })
111
+ ```
112
+
113
+ ### Request Method Options
114
+
115
+ All request methods accept these parameters:
116
+
117
+ ```typescript
118
+ // Method signature example with proper TypeScript syntax
119
+ function exampleUsage<DataT, ErrorT> () {
120
+ // These are the parameters you would use
121
+ return ajax.get<DataT, ErrorT>(
122
+ 'https://api.example.com/endpoint', // URL (string)
123
+ { // CustomFetchOptions (optional)
124
+ params: { id: 123 }
125
+ },
126
+ { // AsyncDataOptions (optional)
127
+ watch: ['someRef']
128
+ }
129
+ )
130
+ }
131
+ ```
132
+
133
+ ## Advanced Examples
134
+
135
+ ### API Module Pattern
136
+
137
+ ```ts
138
+ // api.ts
139
+ export const userApi = {
140
+ getUser: (id: string) =>
141
+ ajax.get<UserData>(`/api/users/${id}`),
142
+
143
+ createUser: (userData: UserCreatePayload) =>
144
+ ajax.post<UserData>('/api/users', { body: userData }),
145
+
146
+ updateUser: (id: string, userData: UserUpdatePayload) =>
147
+ ajax.request<UserData>(`/api/users/${id}`, {
148
+ method: 'PUT',
149
+ body: userData
150
+ })
151
+ }
152
+ ```
153
+
154
+ ### Using in Components
155
+
156
+ ```ts
157
+ // UserProfile.vue
158
+ import { userApi } from './api'
159
+
160
+ // Option 1: Using await
161
+ const { data: user, error, refresh } = await userApi.getUser('123')
162
+
163
+ // Option 2: Using without await
164
+ const { data: user, pending, error, refresh } = userApi.getUser('123')
165
+
166
+ // Using with reactive parameters and watch
167
+ const userId = ref('123')
168
+ const { data: user } = await userApi.getUser(userId.value, {}, {
169
+ watch: [userId] // Will refetch when userId changes
51
170
  })
52
171
  ```
53
172
 
54
173
  ## Types
55
174
 
56
- ### useAsyncDataType
175
+ For detailed type information, see the TypeScript definitions:
57
176
 
58
177
  [use-async-data-type](https://nuxt.com/docs/api/composables/use-async-data#type)
59
178
 
179
+ ### useAsyncDataType
180
+
60
181
  ```ts
61
182
  export declare class CustomFetch {
62
183
  baseURL: string
@@ -71,48 +192,20 @@ export declare class CustomFetch {
71
192
  post<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
72
193
  }
73
194
 
74
- export type FetchMethod = 'options' | 'GET' | 'POST' | 'get' | 'HEAD' | 'PATCH' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'post' | 'head' | 'patch' | 'put' | 'delete' | 'connect' | 'trace' | undefined
195
+ export type FetchMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT' | /* lowercase variants */ 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace' | 'connect' | undefined
196
+
75
197
  export interface CustomFetchOptions extends Omit<FetchOptions, 'method'> {
76
- /** unique key for fetch */
77
- key?: string
78
- /** hash key for fetch, with [customFetch: + url] without query */
198
+ key?: MaybeRefOrGetter<string>
79
199
  immutableKey?: boolean
80
- /** show logs */
81
200
  showLogs?: boolean
82
201
  baseURL?: string
83
- /** is use handler to deal with query or pramas */
84
202
  useHandler?: boolean
85
- /** handler to deal with query or pramas */
86
203
  handler?: (mergedObject: FetchOptions['params'] & FetchOptions['query']) => Record<string, any>
87
- /** offline handler */
88
204
  offline?: () => void
89
205
  }
90
- export interface Interceptors {
91
- onRequest?: FetchOptions['onRequest']
92
- onRequestError?: FetchOptions['onRequestError']
93
- onResponse?: FetchOptions['onResponse']
94
- onResponseError?: FetchOptions['onResponseError']
95
- }
96
- ```
97
-
98
- ## Example
99
-
100
- ```ts
101
- // api.ts
102
- export const getInfo = (params: Record<string, any>) =>
103
- ajax.get<DataT>('/api/get-ip', { params }, {})
104
- ```
105
-
106
- ```ts
107
- // index.vue
108
- import { getInfo } from './ajax'
109
- const { data, error } = await getInfo({
110
- sign: 123
111
- })
112
- console.log(data.value)
113
206
  ```
114
207
 
115
208
  ## Development
116
209
 
117
- - Run `npm run dev:prepare` to generate type stubs.
118
- - Use `npm run dev` to start [playground](./playground) in development mode.
210
+ - Run `npm run dev:prepare` to generate type stubs
211
+ - Use `npm run dev` to start the playground in development mode
package/dist/module.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import * as nuxt_schema from 'nuxt/schema';
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
3
  interface ModuleOptions {
4
4
  }
5
- declare const _default: nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
5
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
6
 
7
7
  export { _default as default };
8
8
  export type { ModuleOptions };
@@ -49,13 +49,22 @@ export class CustomFetch {
49
49
  Object.assign(config, this.baseConfig(config));
50
50
  const generateOptionSegmentsWithConfig = generateOptionSegments(config);
51
51
  if (this.showLogs && import.meta.client) {
52
+ const { body: _body, ...resetConfig } = config;
52
53
  let bodyLogs;
53
54
  try {
54
- bodyLogs = serialize(config.body);
55
+ bodyLogs = serialize(_body);
55
56
  } catch (error) {
56
- console.warn("[Custom Fetch] couldn't serialize `Body:`", error);
57
+ console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
57
58
  }
58
- console.warn("[Custom Fetch] `Request:`", url, "`Query:`", serialize(generateOptionSegmentsWithConfig), " `Body:`", bodyLogs);
59
+ console.warn([
60
+ "\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 [Custom Fetch] \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014",
61
+ `[Request URL]: ${url}`,
62
+ "",
63
+ `[Query]: ${serialize(resetConfig)}`,
64
+ "",
65
+ `[Body]: ${bodyLogs}`,
66
+ "\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014"
67
+ ].join("\n"));
59
68
  }
60
69
  const { onRequest, onRequestError, onResponse, onResponseError, offline, handler, useHandler, showLogs, immutableKey, ...asyncDataOptions } = config;
61
70
  if (import.meta.client && navigator && !navigator.onLine) {
@@ -81,12 +90,6 @@ export class CustomFetch {
81
90
  fns?.(ctx);
82
91
  }
83
92
  });
84
- throw createError({
85
- statusCode: 400,
86
- statusMessage: ctx.error.message,
87
- message: ctx.error.message,
88
- fatal: true
89
- });
90
93
  },
91
94
  onResponse(ctx) {
92
95
  [interceptors.onResponse, onResponse].forEach((fns) => {
@@ -105,12 +108,6 @@ export class CustomFetch {
105
108
  fns?.(ctx);
106
109
  }
107
110
  });
108
- throw createError({
109
- statusCode: 500,
110
- statusMessage: ctx.request.toString(),
111
- message: ctx.response._data,
112
- fatal: true
113
- });
114
111
  }
115
112
  };
116
113
  const hashValue = ["custom_fetch:", url];
@@ -154,8 +151,8 @@ export class CustomFetch {
154
151
  const _ref = options.deep ? ref : shallowRef;
155
152
  options.default ??= () => asyncDataDefaults.value;
156
153
  const asyncData = {
157
- data: _ref(null),
158
- error: _ref(null),
154
+ data: _ref(void 0),
155
+ error: _ref(void 0),
159
156
  status: _ref("idle"),
160
157
  pending: _ref(false),
161
158
  clear: () => clearNuxtData(key.value)
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.11",
4
+ "version": "4.0.0-alpha.13",
5
5
  "packageManager": "pnpm@8.15.3+sha1.64838798f519c18029c1e8a1310e16101fc2eda0",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -37,26 +37,26 @@
37
37
  }
38
38
  },
39
39
  "dependencies": {
40
- "@vue/shared": "^3.5.16",
40
+ "@vue/shared": "^3.5.17",
41
41
  "ohash": "^2.0.11",
42
- "vue": "^3.5.16"
42
+ "vue": "^3.5.17"
43
43
  },
44
44
  "devDependencies": {
45
- "@antfu/eslint-config": "^4.13.3",
45
+ "@antfu/eslint-config": "^4.16.2",
46
46
  "@commitlint/cli": "^19.8.1",
47
47
  "@commitlint/config-conventional": "^19.8.1",
48
- "@nuxt/kit": "3.17.5",
48
+ "@nuxt/kit": "3.17.6",
49
49
  "@nuxt/module-builder": "^1.0.1",
50
- "@nuxt/schema": "3.17.5",
51
- "@types/node": "^22.15.29",
50
+ "@nuxt/schema": "3.17.6",
51
+ "@types/node": "^24.0.10",
52
52
  "changelogen": "^0.6.1",
53
53
  "commitizen": "^4.3.1",
54
- "cz-git": "^1.11.1",
55
- "eslint": "^9.28.0",
54
+ "cz-git": "^1.11.2",
55
+ "eslint": "^9.30.1",
56
56
  "husky": "^9.1.7",
57
- "lint-staged": "^16.1.0",
58
- "nitro": "npm:nitropack@^2.11.12",
59
- "nuxt": "3.17.5",
57
+ "lint-staged": "^16.1.2",
58
+ "nitro": "npm:nitropack@^2.11.13",
59
+ "nuxt": "3.17.6",
60
60
  "typescript": "5.8.3"
61
61
  },
62
62
  "husky": {