@@ -2,11 +2,10 @@ import { ofetch } from 'ofetch'
22import { toast } from 'vue-sonner'
33import type { FetchOptions } from 'ofetch'
44
5- import { simpleCamelcaseKeys } from './camelcase-keys'
6-
75import { API_URL } from '~/constants/env'
86
97import { router } from '../router/router'
8+ import { simpleCamelcaseKeys } from './camelcase-keys'
109import { uuid } from './index'
1110
1211export class SystemError extends Error {
@@ -24,6 +23,7 @@ export class BusinessError extends Error {
2423 message : string | string [ ] ,
2524 public statusCode : number ,
2625 public data ?: unknown ,
26+ public code ?: string | number ,
2727 ) {
2828 super ( Array . isArray ( message ) ? message . join ( ', ' ) : message )
2929 this . name = 'BusinessError'
@@ -73,10 +73,11 @@ export const $api = ofetch.create({
7373 }
7474
7575 const data = response . _data
76- const message = data ?. message || '请求失败'
76+ const message = data ?. error ?. message || data ?. message || '请求失败'
77+ const code = data ?. error ?. code
7778 const displayMsg = Array . isArray ( message ) ? message . join ( ', ' ) : message
7879 toast . error ( displayMsg )
79- throw new BusinessError ( message , status , data )
80+ throw new BusinessError ( message , status , data , code )
8081 } ,
8182} )
8283
@@ -86,27 +87,31 @@ export type RequestOptions<T = unknown> = Omit<FetchOptions<'json'>, 'body'> & {
8687 bypassTransform ?: boolean
8788}
8889
89- /**
90- * 转换响应数据
91- * 1. camelCase 转换
92- * 2. 解包后端包装的数组响应 { data: [...] } -> [...]
93- */
90+ function isPlainObject ( value : unknown ) : value is Record < string , unknown > {
91+ return ! ! value && typeof value === 'object' && ! Array . isArray ( value )
92+ }
93+
94+ function isResponseEnvelope ( value : unknown ) : value is Record < string , unknown > {
95+ return (
96+ isPlainObject ( value ) &&
97+ 'data' in value &&
98+ Object . keys ( value ) . every ( ( key ) => key === 'data' || key === 'meta' )
99+ )
100+ }
101+
94102function transformResponse < T > ( data : unknown , bypass ?: boolean ) : T {
95103 if ( bypass || ! data || typeof data !== 'object' ) {
96104 return data as T
97105 }
98106
99- let result = simpleCamelcaseKeys ( data as Record < string , unknown > )
107+ const result = simpleCamelcaseKeys ( data as Record < string , unknown > )
100108
101- if (
102- result &&
103- typeof result === 'object' &&
104- ! Array . isArray ( result ) &&
105- 'data' in result &&
106- Array . isArray ( result . data ) &&
107- Object . keys ( result ) . length === 1
108- ) {
109- result = result . data
109+ if ( isResponseEnvelope ( result ) ) {
110+ const meta = ( result as any ) . meta
111+ if ( meta && isPlainObject ( meta . pagination ) ) {
112+ return { data : ( result as any ) . data , pagination : meta . pagination } as T
113+ }
114+ return ( result as any ) . data as T
110115 }
111116
112117 return result as T
0 commit comments