li.shaoyi 2 tahun lalu
induk
melakukan
d44e470c50
3 mengubah file dengan 86 tambahan dan 65 penghapusan
  1. TEMPAT SAMPAH
      public/html/ht_cg.docx
  2. 85 64
      src/services/http/index@next.ts
  3. 1 1
      src/services/http/interface.ts

TEMPAT SAMPAH
public/html/ht_cg.docx


+ 85 - 64
src/services/http/index@next.ts

@@ -64,94 +64,107 @@ const httpService = new (class {
         )
     }
 
-    private request = async (url: string, method: Method, payload?: unknown) => {
-        const config = await service.onReady()
-        this.axiosInstance.defaults.baseURL = config.goCommonSearchUrl
-        const requestConfig: AxiosRequestConfig = {
+    commonRequest = async <T>(url: string, method: Method, payload?: unknown, errMsg?: string) => {
+        await service.onReady().then((config) => {
+            this.axiosInstance.defaults.baseURL = config.goCommonSearchUrl
+        })
+
+        const config: AxiosRequestConfig = {
             url,
             method,
         }
+
         if (payload instanceof Object) {
             if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
-                requestConfig.data = payload
+                config.data = payload
             } else {
-                requestConfig.params = payload
+                config.params = payload
             }
-        } else {
-            requestConfig.url = url + (payload ?? '')
         }
-        return this.axiosInstance(requestConfig)
-    }
 
-    commonRequest = async <T>(url: string, method: Method, payload: unknown, errMsg?: string) => {
-        return await this.request(url, method, payload).then((res) => {
-            const data = res.data as T
-            return Promise.resolve(data)
+        return await this.axiosInstance(config).then((res) => {
+            return res.data as T
         }).catch((err) => {
             const msg = err ?? (errMsg ? '请求失败: ' + errMsg : '请求失败,请稍后重试')
             return Promise.reject(msg)
         })
     }
 
-    httpRequest = async <T>(url: string, method: Method, payload: unknown, errMsg?: string) => {
-        return await this.request(url, method, payload).then((res) => {
-            const data = res.data as HttpResponse<T>
-            switch (data.code) {
-                case ResultCode.InvalidToken:
-                    return Promise.reject('令牌无效')
-                case ResultCode.Success:
-                    return Promise.resolve(data)
-                default:
-                    return Promise.reject(data.msg)
-            }
-        }).catch((err) => {
-            const msg = err ?? (errMsg ? '请求失败: ' + errMsg : '请求失败,请稍后重试')
-            return Promise.reject(msg)
-        })
+    httpRequest = async <T extends object>(url: string, method: Method, payload?: unknown, errMsg?: string) => {
+        const res = await this.commonRequest<HttpResponse<T>>(url, method, payload, errMsg)
+
+        switch (res.code) {
+            case ResultCode.InvalidToken:
+                return Promise.reject('令牌无效')
+            case ResultCode.Success:
+                return res
+            default:
+                return Promise.reject(res.msg)
+        }
     }
 })
 
-export const { httpRequest } = httpService
+export const { commonRequest, httpRequest } = httpService
 
 
 function queryLoginData(params: Model.LoginQueryReq) {
-    return httpRequest<HttpResponse<Model.LoginQueryRsp>>('/User/LoginQuery', 'get', params, 'LoginQuery');
+    return httpRequest<Model.LoginQueryRsp[]>('/User/LoginQuery', 'get', params, 'LoginQuery')
 }
 
-interface RequestOptions<Req, Rsp> {
-    params: Req;
-    pagination?: boolean;
-    onSuccess?: (res: Rsp) => void;
-    onFail?: (err: string) => void;
+interface RequestOptions<TParams, TResponse> {
+    params: {
+        page?: number; // 当前页码
+        pagesize?: number; // 每页条数
+    } & TParams;
+    pagination?: boolean; // 数据是否使用分页
+    delay?: number;
+    onSuccess?: (res: TResponse) => void;
+    onError?: (err: string) => void;
+    onFinally?: () => void;
 }
 
-function useRequest<Req extends object, Rsp>(runAsync: (params: Req) => Promise<Rsp>, options: RequestOptions<Req, Rsp>) {
-    const loading = ref(false)
-    const data = ref<Rsp>()
-    const { dataList, filters, total, pageIndex, pageSize, pageCount } = useDataTable<Rsp>()
-    if (options.pagination) {
-
+function useRequest<TParams extends object, TResponse extends HttpResponse<TResponse>>(request: (params: TParams) => Promise<TResponse>, options: RequestOptions<TParams, TResponse>) {
+    const { params, pagination, onSuccess, onError, onFinally } = options
+    const { dataList, filters, total, pageIndex, pageSize, pageCount } = useDataTable<TResponse['data']>({
+        pageSize: params.page,
+        pageIndex: params.pagesize,
+    })
 
-        const defaultParams = {
-            page: pageIndex.value,
-            pagesize: pageSize.value,
-            ...options.params
+    const loading = ref(false)
+    const data = ref<TResponse['data']>()
+
+    // 异步函数
+    const runAsync = async (payload: Partial<TParams> = {}) => {
+        try {
+            loading.value = true
+            if (pagination) {
+                params.page = pageIndex.value
+                params.pagesize = pageIndex.value
+            }
+            const res = await request({ ...params, ...payload })
+            total.value = res.total
+            if (Array.isArray(res.data)) {
+                dataList.value = res.data
+            } else {
+                data.value = res.data
+            }
+            return res
+        } finally {
+            loading.value = false
         }
-
-
     }
 
-    const run = (payload: Partial<Req> = {}) => {
-        runAsync({ ...options.params, ...payload }).then((res) => {
-            if (Array.isArray(res)) {
-                dataList.value = res
-            }
-            options.onSuccess && options.onSuccess(res)
+    // 同步函数
+    const run = (payload: Partial<TParams> = {}) => {
+        runAsync(payload).then((res) => {
+            onSuccess && onSuccess(res)
+        }).catch((err) => {
+            onError && onError(err)
+        }).finally(() => {
+            onFinally && onFinally()
         })
     }
 
-
-
     const cancel = () => {
         console.log('取消请求')
     }
@@ -163,19 +176,27 @@ function useRequest<Req extends object, Rsp>(runAsync: (params: Req) => Promise<
     return {
         loading,
         data,
+        dataList,
+        total,
+        pageIndex,
+        pageSize,
+        pageCount,
+        filters,
+        runAsync,
         run,
         cancel,
     }
 }
 
-const { run, data } = useRequest(queryLoginData, {
-    params: {
-        loginID: 0,
-    },
-    onSuccess: (res) => {
-        console.log(res)
-    },
-})
+// const { run, data, dataList } = useRequest(queryLoginData, {
+//     params: {
+//         loginID: 0,
+//     },
+//     onSuccess: (res) => {
+//         console.log(res)
+//         dataList.value = res.data
+//     },
+// })
 
 /**
  * 获取服务配置地址

+ 1 - 1
src/services/http/interface.ts

@@ -26,7 +26,7 @@ export type CommonParams<T extends Payload = object> = RequestParams<T['req'], T
 /**
  * Http响应结果
  */
-export interface HttpResponse<T> {
+export interface HttpResponse<T = unknown> {
     code: ResultCode;
     msg: string;
     total: number;