import { useAuthStore } from '~/stores/auth' interface ApiResponse { code: number msg: string data: T } async function request( url: string, body: unknown, extraHeaders?: Record ): Promise { const auth = useAuthStore() const router = useRouter() const headers: Record = { 'Content-Type': 'application/json', } if (auth.token) { headers['Authorization'] = auth.token } if (extraHeaders) { Object.assign(headers, extraHeaders) } const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), }) if (!response.ok) { throw new Error(`HTTP error: ${response.status}`) } const result: ApiResponse = await response.json() if (result.code === 18) { auth.logout() router.push('/') throw new Error(result.msg || 'Unauthorized') } if (result.code !== 0) { throw new Error(result.msg || 'Unknown error') } return result.data } export function useApi() { const auth = useAuthStore() async function webApi(method: string, data?: unknown): Promise { const extraHeaders: Record = {} if (auth.currentAppId) { extraHeaders['X-App-Id'] = String(auth.currentAppId) } return request(`/web/api/api_${method}`, data ?? {}, extraHeaders) } async function consoleApi(path: string, data?: unknown): Promise { return request(`/console/api/${path}`, data ?? {}) } async function uploadFile(file: File, path: string): Promise { const cosToken = await webApi<{ upload_url?: string url?: string }>('getcostoken', { path }) const uploadUrl = cosToken.upload_url || cosToken.url || '' const putResponse = await fetch(uploadUrl, { method: 'PUT', headers: { 'Content-Type': file.type || 'application/octet-stream', }, body: file, }) if (!putResponse.ok) { throw new Error(`Upload failed: ${putResponse.status}`) } return uploadUrl.split('?')[0] } return { webApi, consoleApi, uploadFile, } }