Explorar el Código

refactor(http): 统一请求函数返回类型并增强useRequest兼容性

修改http和vue-query模块的请求函数返回类型为HttpRequestResult<T>
优化useRequest钩子以支持同步和异步请求函数
在示例组件中更新请求调用方式
feige996 hace 7 meses
padre
commit
7887b8600c

+ 20 - 17
src/hooks/useRequest.ts

@@ -19,14 +19,14 @@ interface IUseRequestReturn<T, P = undefined> {
 
 /**
  * useRequest是一个定制化的请求钩子,用于处理异步请求和响应。
- * @param func 一个执行异步请求的函数,返回一个包含响应数据的Promise
+ * @param func 一个执行异步请求的函数,返回HttpRequestResult<T>或Promise<HttpRequestResult<T>>
  * @param options 包含请求选项的对象 {immediate, initialData}。
  * @param options.immediate 是否立即执行请求,默认为false。
  * @param options.initialData 初始化数据,默认为undefined。
  * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
  */
 export default function useRequest<T, P = undefined>(
-  func: (args?: P) => HttpRequestResult<T>,
+  func: (args?: P) => HttpRequestResult<T> | Promise<HttpRequestResult<T>>,
   options: IUseRequestOptions<T> = { immediate: false },
 ): IUseRequestReturn<T, P> {
   const loading = ref(false)
@@ -36,21 +36,24 @@ export default function useRequest<T, P = undefined>(
 
   const run = async (args?: P) => {
     loading.value = true
-    const { promise, requestTask: task } = func(args)
-    requestTask = task // Store the requestTask
-    return promise
-      .then((res) => {
-        data.value = res
-        error.value = false
-        return data.value
-      })
-      .catch((err) => {
-        error.value = err
-        throw err
-      })
-      .finally(() => {
-        loading.value = false
-      })
+    try {
+      // 支持同步和异步函数
+      const result = await func(args)
+      const { promise, requestTask: task } = result
+      requestTask = task // Store the requestTask
+
+      const res = await promise
+      data.value = res
+      error.value = false
+      return data.value
+    }
+    catch (err) {
+      error.value = err instanceof Error ? err : new Error('Request failed')
+      throw err
+    }
+    finally {
+      loading.value = false
+    }
   }
 
   const cancel = () => {

+ 2 - 2
src/http/http.ts

@@ -1,5 +1,5 @@
 import type { IDoubleTokenRes } from '@/api/types/login'
-import type { CustomRequestOptions, IResponse } from '@/http/types'
+import type { CustomRequestOptions, HttpRequestResult, IResponse } from '@/http/types'
 import { nextTick } from 'vue'
 import { LOGIN_PAGE } from '@/router/config'
 import { useTokenStore } from '@/store/token'
@@ -10,7 +10,7 @@ import { ResultEnum } from './tools/enum'
 let refreshing = false // 防止重复刷新 token 标识
 let taskQueue: { resolve: (value: any) => void, reject: (reason?: any) => void, options: CustomRequestOptions }[] = [] as { resolve: (value: any) => void, reject: (reason?: any) => void, options: CustomRequestOptions }[] // 刷新 token 请求队列
 
-export function http<T>(options: CustomRequestOptions) {
+export function http<T>(options: CustomRequestOptions): HttpRequestResult<T> {
   let requestTask: UniApp.RequestTask | undefined
   const promise = new Promise<T>((resolve, reject) => {
     requestTask = uni.request({

+ 2 - 2
src/http/vue-query.ts

@@ -1,4 +1,4 @@
-import type { CustomRequestOptions } from '@/http/types'
+import type { CustomRequestOptions, HttpRequestResult } from '@/http/types'
 import { http } from './http'
 
 /*
@@ -10,7 +10,7 @@ export default function request<T = unknown>(
     params?: Record<string, unknown>
     headers?: Record<string, unknown>
   },
-) {
+): HttpRequestResult<T> {
   const requestOptions = {
     url,
     ...options,

+ 8 - 2
src/pages/about/components/request-openapi.vue

@@ -1,5 +1,7 @@
 <script lang="ts" setup>
 import type { UserItem } from '@/service'
+import { ref } from 'vue'
+import useRequest from '@/hooks/useRequest'
 import { infoUsingGet } from '@/service/info'
 
 const loading = ref(false)
@@ -9,7 +11,9 @@ const data = ref<UserItem>()
 async function getUserInfo() {
   try {
     loading.value = true
-    const res = await (await infoUsingGet({})).promise
+    // 直接使用openapi生成的请求,需要解构获取promise
+    const { promise } = await infoUsingGet({})
+    const res = await promise
     console.log(res)
     data.value = res
     error.value = null
@@ -22,7 +26,9 @@ async function getUserInfo() {
     loading.value = false
   }
 }
-const { data: data2, loading: loading2, run } = useRequest(() => infoUsingGet({}), {
+
+// 使用openapi + useRequest生成的请求
+const { data: data2, loading: loading2, run } = useRequest<UserItem>(() => infoUsingGet({}), {
   immediate: false,
 })
 </script>