import http from '@ohos.net.http' import type { ApiResponse } from './Types' import { SDKContext } from './SDKContext' export class HttpClient { static async request( method: http.RequestMethod, path: string, body?: object, query?: Record, ): Promise { const config = SDKContext.getConfig() const token = SDKContext.getToken() const queryPairs: string[] = [] if (query) { for (const key of Object.keys(query)) { const value = query[key] if (value === undefined || value === null || value === '') continue queryPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value instanceof Date ? value.toISOString() : String(value))}`) } } const url = config.apiBaseUrl.replace(/\/$/, '') + path + (queryPairs.length > 0 ? `?${queryPairs.join('&')}` : '') const client = http.createHttp() try { const options: http.HttpRequestOptions = { method, header: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), }, extraData: body ? JSON.stringify(body) : undefined, connectTimeout: 15000, readTimeout: 15000, } const res = await client.request(url, options) const json: ApiResponse = JSON.parse(res.result as string) as ApiResponse if (json.code !== 200) throw new Error(json.message) return json.data } finally { client.destroy() } } static get(path: string, query?: Record): Promise { return HttpClient.request(http.RequestMethod.GET, path, undefined, query) } static post(path: string, body?: object, query?: Record): Promise { return HttpClient.request(http.RequestMethod.POST, path, body, query) } static put(path: string, body?: object, query?: Record): Promise { return HttpClient.request(http.RequestMethod.PUT, path, body, query) } static delete(path: string, query?: Record): Promise { return HttpClient.request(http.RequestMethod.DELETE, path, undefined, query) } }