From 810da0895a333e7a11095352b4103660b4f5b762 Mon Sep 17 00:00:00 2001 From: Tenor Biel Date: Thu, 10 Nov 2016 16:25:18 -0600 Subject: [PATCH] Make response handling more configurable --- lib/index.js | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/index.js b/lib/index.js index 9b6a5a3..31eeae8 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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) { @@ -43,6 +48,7 @@ export class Transport extends LokkaTransport { }; this.endpoint = endpoint; this.handleErrors = options.handleErrors || handleErrors; + this.handleErrorResponse = options.handleErrorResponse || handleErrorResponse; } _buildOptions(payload) { @@ -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); @@ -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)); }); } }