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 => { 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` + } + }) + }) })