diff --git a/README.md b/README.md index f92d8a7..8e940d8 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,20 @@ npm install graphql-client -S ## How To ```javascript -var client = require('graphql-client')({url: 'http://your-host/graphql'}) +var client = require('graphql-client')({ + url: 'http://your-host/graphql', + + // before request hook + onRequest (req) { + // Do whatever you want with `req`, e.g. add JWT auth header + req.headers.set('Authentication', 'Bearer ' + token) + }, + + // response hook + onResponse (res) { + ... + } +}) var query = ` query search ($query: String, $from: Int, $limit: Int) { diff --git a/index.js b/index.js index 38b2cb7..a70d0f0 100644 --- a/index.js +++ b/index.js @@ -8,7 +8,7 @@ function highlightQuery (query, errors) { query.split('\n').forEach(function (row, index) { var line = index + 1 - var lineErrors = locations.filter(function (loc) { return loc.line === line }) + var lineErrors = locations.filter(function (loc) { return loc && loc.line === line }) queryHighlight += row + '\n' @@ -40,7 +40,7 @@ module.exports = function (params) { var headers = new Headers() headers.append('Content-Type', 'application/json') - return fetch(params.url, { + var req = { method: 'POST', body: JSON.stringify({ query: query, @@ -48,7 +48,12 @@ module.exports = function (params) { }), headers: headers, credentials: params.credentials - }).then(function (res) { + } + + if (params.onRequest) params.onRequest(req) + + return fetch(params.url, req).then(function (res) { + if (params.onResponse) params.onResponse(res) return res.json() }).then(function (data) { if (data.errors && data.errors.length) {