-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.service.ts
More file actions
50 lines (43 loc) · 1.3 KB
/
request.service.ts
File metadata and controls
50 lines (43 loc) · 1.3 KB
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
import { HttpResponseDto } from '@shared/dto/responses/abstract/http.response.dto';
import { injectable } from 'tsyringe';
@injectable()
export class RequestService {
private async _fetch<T>(url: string, options: RequestInit): Promise<T> {
const response: Response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...(options.headers ?? {}),
},
});
if (!response.ok) {
let message: string = 'Unexpected error';
try {
const errorJson: HttpResponseDto<T> = await response.json();
message = errorJson?.error ?? message;
} catch {
message = await response.text();
}
throw new Error(message);
}
return response.json();
}
public async get<T>(url: string): Promise<T> {
return await this._fetch<T>(url, { method: 'GET' });
}
public async post<T>(url: string, body: unknown): Promise<T> {
return await this._fetch<T>(url, {
method: 'POST',
body: JSON.stringify(body),
});
}
public async put<T>(url: string, body: unknown): Promise<T> {
return await this._fetch<T>(url, {
method: 'PUT',
body: JSON.stringify(body),
});
}
public async delete<T>(url: string): Promise<T> {
return await this._fetch<T>(url, { method: 'DELETE' });
}
}