-
Notifications
You must be signed in to change notification settings - Fork 2
/
HttpClient.ts
88 lines (80 loc) · 2.5 KB
/
HttpClient.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { REQUEST_TIME_OUT } from '../enum/index.ts'
import { fetch, globalOption } from '../deps.ts'
export interface IHttpOptions {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
body?: any;
headers?: Record<string, string>;
timeout?: number;
}
export interface IHttpResponse {
status: number;
headers?: Record<string, string>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
body: any;
}
export interface IHttpClient {
postAsync(url: string, options: IHttpOptions): Promise<IHttpResponse>;
getAsync(url: string, options?: IHttpOptions): Promise<IHttpResponse>;
}
export class HttpClient implements IHttpClient {
private async getResponse (response:Response) {
const applicationType = response.headers.get('Content-Type')
const checkJson = applicationType === 'application/json'
const bodyString = await response.text()
let body:Record<string, unknown>|undefined
if (bodyString && checkJson) {
body = JSON.parse(bodyString)
}
if (response.status >= 400) {
throw new Error(bodyString || response.statusText)
}
const headers:Record<string, string> = {}
response.headers.forEach((value, key) => {
headers[key] = value
})
return {
status: response.status,
body,
headers
}
}
getAsync (url: string, options?: IHttpOptions): Promise<IHttpResponse> {
const c = new AbortController()
const id = setTimeout(() => c.abort(), (options?.timeout ? options.timeout : REQUEST_TIME_OUT) * 1000)
return fetch(url, {
...globalOption,
method: 'GET',
headers: options?.headers,
signal: c.signal,
keepalive: true
})
.then(this.getResponse)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.catch((error:any) => {
throw error
})
.finally(() => {
clearInterval(id)
})
}
public postAsync (url: string, options: IHttpOptions): Promise<IHttpResponse> {
const c = new AbortController()
const id = setTimeout(() => c.abort(), options.timeout ? options.timeout * 1000 : REQUEST_TIME_OUT * 1000)
return fetch(url, {
...globalOption,
method: 'POST',
headers: options.headers,
body: JSON.stringify(options.body),
signal: c.signal,
keepalive: true
})
.then(this.getResponse)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.catch((error: any) => {
throw error
})
.finally(() => {
clearInterval(id)
})
}
}