import http from '@ohos.net.http' import type { ApiResponse, HttpHeaders } from './Types' import { SDKContext } from './SDKContext' export class HttpClient { static async request( method: http.RequestMethod, path: string, body?: Object, query?: string, ): Promise { const config = SDKContext.getConfig() const token = SDKContext.getToken() const url = config.apiBaseUrl.replace(/\/$/, '') + path + (query ? '?' + query : '') const client = http.createHttp() try { const header: HttpHeaders = { 'Content-Type': 'application/json', } if (token) { header.Authorization = 'Bearer ' + token } const options: http.HttpRequestOptions = { method, header, extraData: body ? JSON.stringify(body) : '', 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?: string): Promise { return HttpClient.request(http.RequestMethod.GET, path, undefined, query) } static post(path: string, body?: Object, query?: string): Promise { return HttpClient.request(http.RequestMethod.POST, path, body, query) } static put(path: string, body?: Object, query?: string): Promise { return HttpClient.request(http.RequestMethod.PUT, path, body, query) } static delete(path: string, query?: string): Promise { return HttpClient.request(http.RequestMethod.DELETE, path, undefined, query) } }