nuxt-custom-fetch 4.0.0-alpha.9 → 4.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 +150 -56
- package/dist/module.d.mts +2 -2
- package/dist/runtime/ajax.js +38 -45
- package/dist/runtime/utils.js +1 -1
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -1,61 +1,183 @@
|
|
|
1
|
-
# Nuxt
|
|
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
|
-
|
|
5
|
+
## Version Compatibility
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
- `v4`: Compatible with Nuxt v3.17.0 or higher
|
|
8
|
+
- `v2`: Compatible with Nuxt v3.0.0 to v3.16.x
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
## Breaking Changes in v4
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
1. `http` method has been removed, use `request` instead
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
## Key Features
|
|
14
15
|
|
|
15
|
-
-
|
|
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
|
|
16
24
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
3. If a reactive object is passed and using `watch`, it will automatically re request
|
|
20
|
-
|
|
21
|
-
## Install
|
|
25
|
+
## Installation
|
|
22
26
|
|
|
23
27
|
```bash
|
|
28
|
+
npm install nuxt-custom-fetch
|
|
29
|
+
# or
|
|
30
|
+
yarn add nuxt-custom-fetch
|
|
31
|
+
# or
|
|
24
32
|
pnpm add nuxt-custom-fetch
|
|
25
33
|
```
|
|
26
34
|
|
|
35
|
+
Then add the module to your `nuxt.config.ts`:
|
|
36
|
+
|
|
27
37
|
```ts
|
|
28
|
-
// nuxt.config.ts
|
|
29
38
|
export default defineNuxtConfig({
|
|
30
39
|
modules: ['nuxt-custom-fetch']
|
|
31
40
|
})
|
|
32
41
|
```
|
|
33
42
|
|
|
34
|
-
## Usage
|
|
43
|
+
## Basic Usage
|
|
35
44
|
|
|
36
|
-
global CustomFetch
|
|
45
|
+
Create a global CustomFetch instance:
|
|
37
46
|
|
|
38
47
|
```ts
|
|
39
48
|
const ajax = new CustomFetch({
|
|
40
|
-
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
|
+
}
|
|
41
63
|
})
|
|
42
64
|
|
|
43
|
-
//
|
|
44
|
-
ajax.get('/api/
|
|
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
|
|
45
88
|
|
|
46
|
-
|
|
89
|
+
### CustomFetch Constructor Options
|
|
47
90
|
|
|
48
|
-
|
|
49
|
-
|
|
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
|
|
50
170
|
})
|
|
51
171
|
```
|
|
52
172
|
|
|
53
173
|
## Types
|
|
54
174
|
|
|
55
|
-
|
|
175
|
+
For detailed type information, see the TypeScript definitions:
|
|
56
176
|
|
|
57
177
|
[use-async-data-type](https://nuxt.com/docs/api/composables/use-async-data#type)
|
|
58
178
|
|
|
179
|
+
### useAsyncDataType
|
|
180
|
+
|
|
59
181
|
```ts
|
|
60
182
|
export declare class CustomFetch {
|
|
61
183
|
baseURL: string
|
|
@@ -70,48 +192,20 @@ export declare class CustomFetch {
|
|
|
70
192
|
post<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
|
|
71
193
|
}
|
|
72
194
|
|
|
73
|
-
export type FetchMethod = '
|
|
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
|
+
|
|
74
197
|
export interface CustomFetchOptions extends Omit<FetchOptions, 'method'> {
|
|
75
|
-
|
|
76
|
-
key?: string
|
|
77
|
-
/** hash key for fetch, with [customFetch: + url] without query */
|
|
198
|
+
key?: MaybeRefOrGetter<string>
|
|
78
199
|
immutableKey?: boolean
|
|
79
|
-
/** show logs */
|
|
80
200
|
showLogs?: boolean
|
|
81
201
|
baseURL?: string
|
|
82
|
-
/** is use handler to deal with query or pramas */
|
|
83
202
|
useHandler?: boolean
|
|
84
|
-
/** handler to deal with query or pramas */
|
|
85
203
|
handler?: (mergedObject: FetchOptions['params'] & FetchOptions['query']) => Record<string, any>
|
|
86
|
-
/** offline handler */
|
|
87
204
|
offline?: () => void
|
|
88
205
|
}
|
|
89
|
-
export interface Interceptors {
|
|
90
|
-
onRequest?: FetchOptions['onRequest']
|
|
91
|
-
onRequestError?: FetchOptions['onRequestError']
|
|
92
|
-
onResponse?: FetchOptions['onResponse']
|
|
93
|
-
onResponseError?: FetchOptions['onResponseError']
|
|
94
|
-
}
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
## Example
|
|
98
|
-
|
|
99
|
-
```ts
|
|
100
|
-
// api.ts
|
|
101
|
-
export const getInfo = (params: Record<string, any>) =>
|
|
102
|
-
ajax.get<DataT>('/api/get-ip', { params }, {})
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
```ts
|
|
106
|
-
// index.vue
|
|
107
|
-
import { getInfo } from './ajax'
|
|
108
|
-
const { data, error } = await getInfo({
|
|
109
|
-
sign: 123
|
|
110
|
-
})
|
|
111
|
-
console.log(data.value)
|
|
112
206
|
```
|
|
113
207
|
|
|
114
208
|
## Development
|
|
115
209
|
|
|
116
|
-
- Run `npm run dev:prepare` to generate type stubs
|
|
117
|
-
- Use `npm run dev` to start
|
|
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
|
|
1
|
+
import * as _nuxt_schema from '@nuxt/schema';
|
|
2
2
|
|
|
3
3
|
interface ModuleOptions {
|
|
4
4
|
}
|
|
5
|
-
declare const _default:
|
|
5
|
+
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
6
6
|
|
|
7
7
|
export { _default as default };
|
|
8
8
|
export type { ModuleOptions };
|
package/dist/runtime/ajax.js
CHANGED
|
@@ -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(
|
|
55
|
+
bodyLogs = serialize(_body);
|
|
55
56
|
} catch (error) {
|
|
56
|
-
console.warn("[Custom Fetch] couldn't serialize
|
|
57
|
+
console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
|
|
57
58
|
}
|
|
58
|
-
console.warn(
|
|
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) {
|
|
@@ -64,53 +73,37 @@ export class CustomFetch {
|
|
|
64
73
|
const interceptors = this._interceptors;
|
|
65
74
|
const _config = reactive({ ...asyncDataOptions });
|
|
66
75
|
const defaultOptions = {
|
|
67
|
-
onRequest(ctx) {
|
|
68
|
-
[interceptors.onRequest, onRequest].
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
fns?.(ctx);
|
|
76
|
+
async onRequest(ctx) {
|
|
77
|
+
const allFns = [interceptors.onRequest, onRequest].flat();
|
|
78
|
+
for (const fn of allFns) {
|
|
79
|
+
if (fn) {
|
|
80
|
+
await fn(ctx);
|
|
73
81
|
}
|
|
74
|
-
}
|
|
82
|
+
}
|
|
75
83
|
},
|
|
76
|
-
onRequestError(ctx) {
|
|
77
|
-
[interceptors.onRequestError, onRequestError].
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
fns?.(ctx);
|
|
84
|
+
async onRequestError(ctx) {
|
|
85
|
+
const allFns = [interceptors.onRequestError, onRequestError].flat();
|
|
86
|
+
for (const fn of allFns) {
|
|
87
|
+
if (fn) {
|
|
88
|
+
await fn(ctx);
|
|
82
89
|
}
|
|
83
|
-
}
|
|
84
|
-
throw createError({
|
|
85
|
-
statusCode: 400,
|
|
86
|
-
statusMessage: ctx.error.message,
|
|
87
|
-
message: ctx.error.message,
|
|
88
|
-
fatal: true
|
|
89
|
-
});
|
|
90
|
+
}
|
|
90
91
|
},
|
|
91
|
-
onResponse(ctx) {
|
|
92
|
-
[interceptors.onResponse, onResponse].
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
fns?.(ctx);
|
|
92
|
+
async onResponse(ctx) {
|
|
93
|
+
const allFns = [interceptors.onResponse, onResponse].flat();
|
|
94
|
+
for (const fn of allFns) {
|
|
95
|
+
if (fn) {
|
|
96
|
+
await fn(ctx);
|
|
97
97
|
}
|
|
98
|
-
}
|
|
98
|
+
}
|
|
99
99
|
},
|
|
100
|
-
onResponseError(ctx) {
|
|
101
|
-
[interceptors.onResponseError, onResponseError].
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
fns?.(ctx);
|
|
100
|
+
async onResponseError(ctx) {
|
|
101
|
+
const allFns = [interceptors.onResponseError, onResponseError].flat();
|
|
102
|
+
for (const fn of allFns) {
|
|
103
|
+
if (fn) {
|
|
104
|
+
await fn(ctx);
|
|
106
105
|
}
|
|
107
|
-
}
|
|
108
|
-
throw createError({
|
|
109
|
-
statusCode: 500,
|
|
110
|
-
statusMessage: ctx.request.toString(),
|
|
111
|
-
message: ctx.response._data,
|
|
112
|
-
fatal: true
|
|
113
|
-
});
|
|
106
|
+
}
|
|
114
107
|
}
|
|
115
108
|
};
|
|
116
109
|
const hashValue = ["custom_fetch:", url];
|
|
@@ -154,8 +147,8 @@ export class CustomFetch {
|
|
|
154
147
|
const _ref = options.deep ? ref : shallowRef;
|
|
155
148
|
options.default ??= () => asyncDataDefaults.value;
|
|
156
149
|
const asyncData = {
|
|
157
|
-
data: _ref(
|
|
158
|
-
error: _ref(
|
|
150
|
+
data: _ref(void 0),
|
|
151
|
+
error: _ref(void 0),
|
|
159
152
|
status: _ref("idle"),
|
|
160
153
|
pending: _ref(false),
|
|
161
154
|
clear: () => clearNuxtData(key.value)
|
package/dist/runtime/utils.js
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-custom-fetch",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "4.0.
|
|
4
|
+
"version": "4.0.1",
|
|
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.
|
|
40
|
+
"@vue/shared": "^3.5.17",
|
|
41
41
|
"ohash": "^2.0.11",
|
|
42
|
-
"vue": "^3.5.
|
|
42
|
+
"vue": "^3.5.17"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@antfu/eslint-config": "^4.
|
|
45
|
+
"@antfu/eslint-config": "^4.17.0",
|
|
46
46
|
"@commitlint/cli": "^19.8.1",
|
|
47
47
|
"@commitlint/config-conventional": "^19.8.1",
|
|
48
|
-
"@nuxt/kit": "
|
|
48
|
+
"@nuxt/kit": "4.0.0",
|
|
49
49
|
"@nuxt/module-builder": "^1.0.1",
|
|
50
|
-
"@nuxt/schema": "
|
|
51
|
-
"@types/node": "^
|
|
52
|
-
"changelogen": "^0.6.
|
|
50
|
+
"@nuxt/schema": "4.0.0",
|
|
51
|
+
"@types/node": "^24.0.14",
|
|
52
|
+
"changelogen": "^0.6.2",
|
|
53
53
|
"commitizen": "^4.3.1",
|
|
54
|
-
"cz-git": "^1.
|
|
55
|
-
"eslint": "^9.
|
|
54
|
+
"cz-git": "^1.12.0",
|
|
55
|
+
"eslint": "^9.31.0",
|
|
56
56
|
"husky": "^9.1.7",
|
|
57
|
-
"lint-staged": "^16.
|
|
58
|
-
"nitro": "npm:nitropack@^2.
|
|
59
|
-
"nuxt": "
|
|
57
|
+
"lint-staged": "^16.1.2",
|
|
58
|
+
"nitro": "npm:nitropack@^2.12.0",
|
|
59
|
+
"nuxt": "4.0.0",
|
|
60
60
|
"typescript": "5.8.3"
|
|
61
61
|
},
|
|
62
62
|
"husky": {
|