Skip to content

Commit ae0d2af

Browse files
improve header handling in HTTP client
centralize addition of default and content-type headers in «fetch» ensure HTTP method is always specified simplify header logic in «get», «post», «put», and «delete» functions prevents missing or incorrect headers for requests
1 parent db4451c commit ae0d2af

File tree

1 file changed

+19
-20
lines changed

1 file changed

+19
-20
lines changed

public/dashboard-assistant/modules/common/http/infrastructure/window-fetch-http-client.ts

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,23 @@ export class WindowFetchHttpClient implements HttpClient {
44
private defaultHeaders = { 'osd-xsrf': 'kibana' };
55

66
private fetch(url: string, options: RequestInit) {
7+
if (!options.method) {
8+
throw new Error('HTTP method is required');
9+
}
10+
11+
options.headers = {
12+
...options.headers,
13+
...this.defaultHeaders,
14+
};
15+
16+
if (['POST', 'PUT'].includes(options.method)) {
17+
options.headers = {
18+
'Content-Type': 'application/json',
19+
// Merge any additional headers provided in options
20+
...options.headers,
21+
};
22+
}
23+
724
return window.fetch(url, options).then(async response => {
825
if (!response.ok) {
926
const error = new Error(`HTTP error! status: ${response.status}`);
@@ -17,42 +34,24 @@ export class WindowFetchHttpClient implements HttpClient {
1734
constructor() {}
1835

1936
async get<T = any>(url: string): Promise<T> {
20-
return await this.fetch(url, {
21-
method: 'GET',
22-
headers: {
23-
...this.defaultHeaders,
24-
},
25-
});
37+
return await this.fetch(url, { method: 'GET' });
2638
}
2739

2840
async post<T = any>(url: string, data?: any): Promise<T> {
2941
return await this.fetch(url, {
3042
method: 'POST',
31-
headers: {
32-
...this.defaultHeaders,
33-
'Content-Type': 'application/json',
34-
},
3543
body: data !== undefined ? JSON.stringify(data) : undefined,
3644
});
3745
}
3846

3947
async put<T = any>(url: string, data?: any): Promise<T> {
4048
return await this.fetch(url, {
4149
method: 'PUT',
42-
headers: {
43-
...this.defaultHeaders,
44-
'Content-Type': 'application/json',
45-
},
4650
body: data !== undefined ? JSON.stringify(data) : undefined,
4751
});
4852
}
4953

5054
async delete<T = any>(url: string): Promise<T> {
51-
return await this.fetch(url, {
52-
method: 'DELETE',
53-
headers: {
54-
...this.defaultHeaders,
55-
},
56-
});
55+
return await this.fetch(url, { method: 'DELETE' });
5756
}
5857
}

0 commit comments

Comments
 (0)