Skip to content

Commit 6942e15

Browse files
committed
Extract base request method
1 parent cc1cf02 commit 6942e15

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

src/client.js

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export default class Client {
66
const config = { ...defaults, ...options };
77

88
const headers = {
9+
'Content-Type': 'application/json',
910
'User-Agent': config.userAgent,
1011
Authorization: `Bearer ${apiKey}`,
1112
};
@@ -15,31 +16,39 @@ export default class Client {
1516
this.headers = headers;
1617
}
1718

19+
/**
20+
* Make a GET request
21+
* @param {string} path - API endpoint path
22+
* @returns {Promise<Object>} Response data
23+
*/
1824
async get(path) {
19-
try {
20-
const response = await fetch(this.baseURL + path, {
21-
headers: this.headers,
22-
timeout: this.timeout,
23-
});
24-
25-
if (!response.ok) {
26-
throw new Error(await response.text());
27-
}
28-
29-
return await response.json();
30-
} catch (e) {
31-
return handleError(e);
32-
}
25+
return this.request(path, {
26+
method: 'GET',
27+
});
3328
}
3429

30+
/**
31+
* Make a POST request
32+
* @param {string} path - API endpoint path
33+
* @param {Object} data - Request body data
34+
* @returns {Promise<Object>} Response data
35+
*/
3536
async post(path, data) {
37+
return this.request(path, {
38+
method: 'POST',
39+
body: JSON.stringify(data),
40+
});
41+
}
42+
43+
async request(path, options = {}) {
3644
try {
37-
const response = await fetch(this.baseURL + path, {
38-
method: 'POST',
39-
headers: Object.assign(this.headers, { 'Content-Type': 'application/json' }),
40-
body: JSON.stringify(data),
45+
const fetchOptions = {
46+
headers: this.headers,
4147
timeout: this.timeout,
42-
});
48+
...options,
49+
};
50+
51+
const response = await fetch(this.baseURL + path, fetchOptions);
4352

4453
if (!response.ok) {
4554
throw new Error(await response.text());

0 commit comments

Comments
 (0)