Skip to content

Commit

Permalink
Throw if server responds not ok
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Jan 14, 2024
1 parent 57f210c commit a65bbd4
Showing 1 changed file with 25 additions and 3 deletions.
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

0 comments on commit a65bbd4

Please sign in to comment.