49 行
1.5 KiB
Plaintext
49 行
1.5 KiB
Plaintext
import http from '@ohos.net.http'
|
|
import type { ApiResponse } from './Types'
|
|
import { SDKContext } from './SDKContext'
|
|
|
|
export class HttpClient {
|
|
static async request<T>(method: http.RequestMethod, path: string, body?: object): Promise<T> {
|
|
const config = SDKContext.getConfig()
|
|
const token = SDKContext.getToken()
|
|
const url = config.apiBaseUrl.replace(/\/$/, '') + path
|
|
|
|
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<T> = JSON.parse(res.result as string) as ApiResponse<T>
|
|
if (json.code !== 200) throw new Error(json.message)
|
|
return json.data
|
|
} finally {
|
|
client.destroy()
|
|
}
|
|
}
|
|
|
|
static get<T>(path: string): Promise<T> {
|
|
return HttpClient.request<T>(http.RequestMethod.GET, path)
|
|
}
|
|
|
|
static post<T>(path: string, body?: object): Promise<T> {
|
|
return HttpClient.request<T>(http.RequestMethod.POST, path, body)
|
|
}
|
|
|
|
static put<T>(path: string, body?: object): Promise<T> {
|
|
return HttpClient.request<T>(http.RequestMethod.PUT, path, body)
|
|
}
|
|
|
|
static delete<T>(path: string): Promise<T> {
|
|
return HttpClient.request<T>(http.RequestMethod.DELETE, path)
|
|
}
|
|
}
|