import { useRequestFetch, useRuntimeConfig } from '#imports' import { MODULES_API_URL, SERVER_API_URL } from '@/config/setting' import { getTenantId } from '@/utils/domain' import { getToken } from '@/utils/token-util' type RequestConfig = { params?: Record data?: any headers?: Record responseType?: 'json' | 'blob' | 'text' | 'arrayBuffer' } type AxiosLikeResponse = { data: T } type NuxtFetch = ReturnType type NuxtFetchOptions = NonNullable[1]> type NuxtFetchMethod = NonNullable function getFetch(): NuxtFetch { try { return useRequestFetch() } catch { return globalThis.$fetch as unknown as NuxtFetch } } function normalizeUrl(url: string) { const config = useRuntimeConfig() const serverBase = config.public.serverApiBase const modulesBase = config.public.modulesApiBase if (url.startsWith(serverBase)) { return SERVER_API_URL + url.slice(serverBase.length) } if (url.startsWith(modulesBase)) { return MODULES_API_URL + url.slice(modulesBase.length) } return url } function mergeHeaders(headers?: Record) { const config = useRuntimeConfig() const tenantId = headers?.TenantId ?? headers?.tenantId ?? getTenantId(String(config.public.tenantId)) const token = getToken() const merged: Record = { TenantId: String(tenantId) } if (token) { merged.Authorization = token } if (headers) { for (const [key, value] of Object.entries(headers)) { if (value === undefined || value === null) continue merged[key] = String(value) } } return merged } function withDefaultModuleBase(url: string) { if (url.startsWith('http://') || url.startsWith('https://')) return url if (url.startsWith('/api/')) return url if (url.startsWith(SERVER_API_URL) || url.startsWith(MODULES_API_URL)) return url if (!url.startsWith('/')) return MODULES_API_URL + '/' + url return MODULES_API_URL + url } async function request( method: NuxtFetchMethod, url: string, body?: any, config: RequestConfig = {} ): Promise> { const $fetch = getFetch() const normalized = withDefaultModuleBase(normalizeUrl(url)) const data = await $fetch(normalized, { method, query: config.params, body: body ?? config.data, headers: mergeHeaders(config.headers), responseType: config.responseType as any }) return { data } } const requestClient = { get: (url: string, config?: RequestConfig) => request('GET', url, undefined, config), delete: (url: string, config?: RequestConfig) => request('DELETE', url, undefined, config), post: (url: string, data?: any, config?: RequestConfig) => request('POST', url, data, config), put: (url: string, data?: any, config?: RequestConfig) => request('PUT', url, data, config) } export default requestClient