From 866fd60f84e5e737d70db4fc7be8ddda6e07bcfa Mon Sep 17 00:00:00 2001 From: Gregor Date: Mon, 7 Jan 2019 22:57:10 -0800 Subject: [PATCH 1/2] =?UTF-8?q?test:=20don=E2=80=99t=20send=20empty=20vari?= =?UTF-8?q?ables=20object?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/graphql-test.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/graphql-test.js b/test/graphql-test.js index 50112a99..fd46b8a0 100644 --- a/test/graphql-test.js +++ b/test/graphql-test.js @@ -142,4 +142,23 @@ describe('graphql()', () => { repo: 'graphql.js' }) }) + + it('Don’t send empty variables object', () => { + const query = '{ viewer { login } }' + + mockable.fetch = fetchMock.sandbox() + .post('https://api.github.com/graphql', (url, options) => { + const body = JSON.parse(options.body) + expect(body.query).to.equal(query) + expect(body.variables).to.equal(undefined) + + return { data: {} } + }) + + return graphql(query, { + headers: { + authorization: `token secret123` + } + }) + }) }) From 070efd00f382854def5f74d9f778aae957b9d6df Mon Sep 17 00:00:00 2001 From: Gregor Date: Mon, 7 Jan 2019 22:57:45 -0800 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20don=E2=80=99t=20send=20empty=20varia?= =?UTF-8?q?bles=20object?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/graphql.js | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lib/graphql.js b/lib/graphql.js index 637dcab8..6e5a016e 100644 --- a/lib/graphql.js +++ b/lib/graphql.js @@ -5,24 +5,25 @@ const GraphqlError = require('./error') const NON_VARIABLE_OPTIONS = ['method', 'baseUrl', 'url', 'headers', 'request', 'query'] function graphql (request, query, options) { - const requestOptions = { - variables: {} - } - if (typeof query === 'string') { options = Object.assign({ query }, options) } else { options = query } - Object.keys(options).forEach(key => { + const requestOptions = Object.keys(options).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { - requestOptions[key] = options[key] - return + result[key] = options[key] + return result + } + + if (!result.variables) { + result.variables = {} } - requestOptions.variables[key] = options[key] - }) + result.variables[key] = options[key] + return result + }, {}) return request(requestOptions) .then(response => {