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

Make response handling more configurable #21

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
25 changes: 16 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ function handleErrors(errors, data) {
throw error;
}

// the default error response handler
function handleErrorResponse(response) {
throw new Error(`Invalid status code: ${response.status}`);
}

export class Transport extends LokkaTransport {
constructor(endpoint, options = {}) {
if (!endpoint) {
Expand All @@ -43,6 +48,7 @@ export class Transport extends LokkaTransport {
};
this.endpoint = endpoint;
this.handleErrors = options.handleErrors || handleErrors;
this.handleErrorResponse = options.handleErrorResponse || handleErrorResponse;
}

_buildOptions(payload) {
Expand All @@ -66,6 +72,14 @@ export class Transport extends LokkaTransport {
return options;
}

handleResponseBody ({data, errors}) {
if (errors) {
return this.handleErrors(errors, data);
}

return this.handleResponse(data);
}

send(query, variables, operationName) {
const payload = {query, variables, operationName};
const options = this._buildOptions(payload);
Expand All @@ -74,17 +88,10 @@ export class Transport extends LokkaTransport {
// 200 is for success
// 400 is for bad request
if (response.status !== 200 && response.status !== 400) {
throw new Error(`Invalid status code: ${response.status}`);
}

return response.json();
}).then(({data, errors}) => {
if (errors) {
this.handleErrors(errors, data);
return null;
return this.handleErrorResponse(response);
}

return data;
return response.json().then(body => this.handleResponseBody(body));
});
}
}
Expand Down