Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw error if server responds with non-OK HTTP status #82

Merged
merged 1 commit into from
Jan 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ const getURI = (id, projection) =>

const requiredFields = ['extensionId', 'clientId', 'refreshToken'];

function throwIfNotOk(request, response) {
if (!request.ok) {
const error = new Error(request.statusText ?? 'Unknown error');
error.response = response;
throw error;
}
}

class APIClient {
constructor(options) {
if (typeof fetch !== 'function') {
Expand Down Expand Up @@ -46,7 +54,11 @@ class APIClient {
body: readStream,
});

return request.json();
const response = await request.json();

throwIfNotOk(request, response);

return response;
}

async publish(target = 'default', token = this.fetchToken()) {
Expand All @@ -57,7 +69,11 @@ class APIClient {
headers: this._headers(await token),
});

return request.json();
const response = await request.json();

throwIfNotOk(request, response);

return response;
}

async get(projection = 'DRAFT', token = this.fetchToken()) {
Expand All @@ -68,7 +84,11 @@ class APIClient {
headers: this._headers(await token),
});

return request.json();
const response = await request.json();

throwIfNotOk(request, response);

return response;
}

async fetchToken() {
Expand All @@ -91,6 +111,8 @@ class APIClient {
},
});

await throwIfNotOk(request);

const response = await request.json();

return response.access_token;
Expand Down