nuxt-custom-fetch 2.0.4 → 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.4"
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
2
  import { createError, reactive, ref, toValue, unref, useAsyncData, useNuxtApp } from "#imports";
3
- const Noop = () => {
4
- };
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) {
@@ -56,47 +51,32 @@ export class CustomFetch {
56
51
  const { useHandler = true, handler, query = {}, params = {} } = config;
57
52
  const baseHandler = handler || this.baseHandler;
58
53
  const _name = Object.keys(query).length ? "query" : "params";
59
- const mergeObj = { ...query, ...params };
54
+ const mergeObj = {
55
+ ...query,
56
+ ...params
57
+ };
60
58
  if (useHandler && baseHandler && typeof baseHandler === "function") {
61
- return {
62
- [_name]: baseHandler(mergeObj)
63
- };
59
+ return { [_name]: baseHandler(mergeObj) };
64
60
  }
65
- return {
66
- [_name]: {
67
- ...mergeObj
68
- }
69
- };
61
+ return { [_name]: { ...mergeObj } };
70
62
  }
71
63
  http(url, config, options = {}) {
72
64
  config.baseURL = config?.baseURL || this.baseURL;
73
65
  Object.assign(config, this.baseConfig(config));
66
+ const { onRequest, onRequestError, onResponse, onResponseError, offline, handler, useHandler, immutableKey, ...restAjaxConfig } = config;
74
67
  if (process.client && navigator && !navigator.onLine) {
75
- config.offline && config.offline();
68
+ if (offline) {
69
+ offline();
70
+ }
76
71
  }
77
72
  const interceptors = this.interceptors;
78
- const {
79
- onRequest,
80
- onRequestError,
81
- onResponse,
82
- onResponseError,
83
- offline,
84
- handler,
85
- useHandler,
86
- immutableKey,
87
- ...restAjaxConfig
88
- } = config;
89
- const _config = reactive({
90
- ...restAjaxConfig
91
- });
73
+ const _config = reactive({ ...restAjaxConfig });
92
74
  const defaultOptions = {
93
75
  onRequest(ctx) {
94
- [interceptors.onRequest, onRequest].map((fn) => fn && fn(ctx));
76
+ [interceptors.onRequest, onRequest].forEach((fn) => fn?.(ctx));
95
77
  },
96
78
  onRequestError(ctx) {
97
- [interceptors.onRequestError, onRequestError].map(
98
- (fn) => fn && fn(ctx)
99
- );
79
+ [interceptors.onRequestError, onRequestError].forEach((fn) => fn?.(ctx));
100
80
  throw createError({
101
81
  statusCode: ctx.error.statusCode,
102
82
  statusMessage: ctx.error.message,
@@ -105,13 +85,15 @@ export class CustomFetch {
105
85
  });
106
86
  },
107
87
  onResponse(ctx) {
108
- interceptors.onResponse && interceptors.onResponse(ctx);
109
- onResponse && onResponse(ctx);
88
+ if (interceptors.onResponse) {
89
+ interceptors.onResponse(ctx);
90
+ }
91
+ if (onResponse) {
92
+ onResponse(ctx);
93
+ }
110
94
  },
111
95
  onResponseError(ctx) {
112
- [interceptors.onResponseError, onResponseError].map(
113
- (fn) => fn && fn(ctx)
114
- );
96
+ [interceptors.onResponseError, onResponseError].forEach((fn) => fn?.(ctx));
115
97
  throw createError({
116
98
  statusCode: ctx.response.status,
117
99
  statusMessage: ctx.request.toString(),
@@ -180,13 +162,15 @@ export class CustomFetch {
180
162
  return useAsyncData(config.key || key, _handler, options);
181
163
  }
182
164
  get(url, config = {}, options) {
183
- return this.http(url, { ...config, method: "GET" }, options);
165
+ return this.http(url, {
166
+ ...config,
167
+ method: "GET"
168
+ }, options);
184
169
  }
185
170
  post(url, config = {}, options) {
186
- return this.http(
187
- url,
188
- { ...config, method: "POST" },
189
- options
190
- );
171
+ return this.http(url, {
172
+ ...config,
173
+ method: "POST"
174
+ }, options);
191
175
  }
192
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.4",
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