/
RestClient.ts
66 lines (54 loc) 路 1.9 KB
/
RestClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { makeRequest } from './makeRequest'
const DEFAULT_BASE_URL = import.meta.env.PROD ? window.location.origin : import.meta.env.VITE_KUMA_API_SERVER_URL
export class RestClient {
/**
* The API base URL. **Will always be stored without a trailing slash**.
*/
_baseUrl: string = DEFAULT_BASE_URL
/**
* The absolute API base URL used in all requests. Includes its base path segment if one is set.
*/
get baseUrl() {
return this._baseUrl
}
/**
* @param baseUrlOrPath the API base URL or the API base path
*/
set baseUrl(baseUrlOrPath: string) {
if (baseUrlOrPath.startsWith('http')) {
this._baseUrl = trimTrailingSlashes(baseUrlOrPath)
} else {
const basePath = trimSlashes(baseUrlOrPath)
this._baseUrl = [DEFAULT_BASE_URL, basePath].filter((segment) => segment !== '').join('/')
}
}
/**
* Performs a network request using the GET method.
*
* @returns the response鈥檚 de-serialized data.
*/
async get(path: string, options?: RequestInit & { params?: any }): Promise<any> {
const processedOptions: RequestInit & { params?: any } = options ?? {}
processedOptions.method = 'GET'
const { data } = await this.raw(path, processedOptions)
return data
}
/**
* Performs a network request.
*
* @returns the response鈥檚 de-serialized data (when applicable) and the raw `Response` object.
*/
async raw(urlOrPath: string, options?: RequestInit & { params?: any }): Promise<{ response: Response, data: any }> {
const url = urlOrPath.startsWith('http') ? urlOrPath : [this.baseUrl, urlOrPath].join('/')
return makeRequest(url, options)
}
}
function trimTrailingSlashes(str: string): string {
return str.replace(/\/+$/, '')
}
function trimLeadingSlashes(str: string): string {
return str.replace(/^\/+/, '')
}
function trimSlashes(str: string): string {
return trimTrailingSlashes(trimLeadingSlashes(str))
}