Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created May 30, 2017 14:46
Show Gist options
  • Select an option

  • Save n1ru4l/cb24401592417bda7fad989d416f0b9f to your computer and use it in GitHub Desktop.

Select an option

Save n1ru4l/cb24401592417bda7fad989d416f0b9f to your computer and use it in GitHub Desktop.

Revisions

  1. n1ru4l created this gist May 30, 2017.
    42 changes: 42 additions & 0 deletions HTTPGetRequestForQueriesInterface.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    import { HTTPFetchNetworkInterface, printAST } from 'apollo-client';


    /**
    * Serialize a object to a query string
    * @source https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object#comment47677757_18116302
    */
    function serialize( obj ) {
    return `?` + Object.keys(obj).map(k => k + `=` + encodeURIComponent(obj[k])).join(`&`);
    }

    class HTTPGetRequestForQueriesInterface extends HTTPFetchNetworkInterface {
    fetchFromRemoteEndpoint({ request, options }) {
    const isQuery = request.query.definitions[0].operation === `query`;
    if (!isQuery) {
    return super.fetchFromRemoteEndpoint({ request, options });
    }

    const opts = Object.assign({}, this._opts, {
    method: `GET`,
    headers: Object.assign({
    Accept: `*/*`,
    'Content-Type': `application/json`,
    }, (options.headers || {})),
    });

    const query = printAST(request.query)
    .replace(/(?:\r\n|\r|\n)/g, ``)
    .replace(/\s\s+/g, ` `);
    const variables = JSON.stringify(request.variables);
    const { operationName } = request;

    const getParams = {
    query,
    variables,
    operationName,
    };
    return fetch(this._uri + serialize(getParams), opts);
    }
    }

    export default HTTPGetRequestForQueriesInterface