GithubHelp home page GithubHelp logo

jasonkuhrt / graphql-request Goto Github PK

View Code? Open in Web Editor NEW
5.7K 32.0 305.0 1.98 MB

Minimal GraphQL client

License: MIT License

TypeScript 99.34% JavaScript 0.66%
graphql graphql-client nodejs typescript lightweight graphql-request

graphql-request's Introduction

graphql-request

Minimal GraphQL client supporting Node and browsers for scripts or simple apps

GitHub Action npm version

Highlights

  • Most simple & lightweight GraphQL client
  • Promise-based API (works with async / await)
  • Pure ESM package
  • First class TypeScript support
    • Including TypedDocumentNode
  • Isomorphic (works in both Nodejs and Browsers)

Install

npm add graphql-request graphql

Quick Start

Send a GraphQL document using a static request function:

import { gql, request } from 'graphql-request'

const document = gql`
  {
    company {
      ceo
    }
  }
`
await request('https://api.spacex.land/graphql/', document)

The function can be passed a configuration object for more complex cases:

await request({
  url,
  document,
  variables,
  requestHeaders,
})

A class is available for constructing your own instances:

import { gql, GraphQLClient } from 'graphql-request'

const document = gql`
  {
    company {
      ceo
    }
  }
`
const endpoint = 'https://api.spacex.land/graphql/'
const client = new GraphQLClient(endpoint)
await client.request(document)

Examples

Node Version Support

We only (officially) support versions of Nodejs of the following status:

  • Current
  • LTS
  • Maintenance and end of life not yet reached

So for example on Oct 24 2023 that would mean these versions: 18, 20, 21.

Any issue that exists solely for an unsupported version of Nodejs will be rejected (not worked on).

Reference

⚠️ This reference is incomplete. Check out the examples for more reference material.

Configuration

ErrorPolicy

By default GraphQLClient will throw when an error is received. However, sometimes you still want to resolve the (partial) data you received. You can define errorPolicy in the GraphQLClient constructor.

const client = new GraphQLClient(endpoint, { errorPolicy: 'all' })
None (default)

Allow no errors at all. If you receive a GraphQL error the client will throw.

Ignore

Ignore incoming errors and resolve like no errors occurred

All

Return both the errors and data, only works with rawRequest.

IgnoreOperationName

OperationName has been introduced to address issues reported here Support operation name, However, on certain occasions this information may not be needed in requests. In such cases, you might consider ignoring operationName to avoid the extraction steps currently performed by a parsing operation when the document is provided in string format.

By default the GraphQLClient tries to extract the operationName from the document. You can define excludeOperationName in the constructor of GraphQLClient to avoid the extraction process if it is not needed. This can be useful if you don't use operationName and want to optimise queries by reducing the amount of computation as much as possible, especially if we are in a context where we are using documents in string format to reduce bundle size.

// example where the operation name is not ignored
const client = new GraphQLClient(endpoint, {
  method: 'POST',
})
// example in which the operation name is ignored
const client = new GraphQLClient(endpoint, {
  method: 'POST',
  excludeOperationName: true,
})

Knowledge Base

Why was the file upload feature taken away? Will it return?

In this issue we decided to make this library more stable and maintainable. In principal the feature is still in scope of this library and will make a return when we find time to do the feature right.

Why do I have to install graphql?

graphql-request uses methods exposed by the graphql package to handle some internal logic. On top of that, for TypeScript users, some types are used from the graphql package to provide better typings.

Do I need to wrap my GraphQL documents inside the gql template exported by graphql-request?

No. It is there for convenience so that you can get the tooling support like automatic formatting and syntax highlighting. You can use gql from graphql-tag if you need it for some reason too.

What sets graphql-request apart from other clients like Apollo, Relay, etc.?

graphql-request is the most minimal and simplest to use GraphQL client. It's perfect for small scripts or simple apps.

Compared to GraphQL clients like Apollo or Relay, graphql-request doesn't have a built-in cache and has no integrations for frontend frameworks. The goal is to keep the package and API as minimal as possible.

graphql-request's People

Contributors

brikou avatar charlypoly avatar dependabot[bot] avatar geoffreyhervet avatar greenkeeper[bot] avatar jasonkuhrt avatar jjangga0214 avatar jonkoops avatar kuldar avatar lukehedger avatar lyubo avatar marhaupe avatar mydea avatar renovate-bot avatar renovate[bot] avatar rickvian avatar ricsitoth avatar ritchieanesco avatar robertobadalamenti avatar romanhotsiy avatar schickling avatar scottburch avatar shimabukuromeg avatar shivan-eyespace avatar shusson avatar simenandre avatar simenb avatar stphnnnn avatar tianqiwuben avatar timsuchanek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-request's Issues

requests with fragments fail

Don't know is this related to prisma-labs/prisma-binding#182, but can be

import {request} from 'graphql-request'
import {collapseArticle} from "../utils";
import {
  ArticleFlatFragment,
  ArticleTranslationFlatFragment,
  TagFlatFragment,
  TagLabelFlatFragment,
  TypeFlatFragment,
  TypeLabelFlatFragment
} from "../../schema/generated/mysql.fragments"; // fragments are generated by my own

const fragments = {
  ArticleFlatFragment,
  ArticleTranslationFlatFragment,
  TagFlatFragment,
  TagLabelFlatFragment,
  TypeFlatFragment,
  TypeLabelFlatFragment
};

// Not using TagFragment and TypeFragment to not load articles recursively
export const articleReturn = `{
  ...ArticleFlat 
  translations(where: {lang: $lang}, first: 1) { ...ArticleTranslationFlat }
  type ${require('../type/typesLocalized.resolvers').typeReturn}
  tags ${require('../tag/tagsLocalized.resolvers').tagReturn}
}`;

export async function articlesLocalized(_, args, ctx, info) {
  const req = `query($lang: String!) { articles ${articleReturn} } ${Object.values(fragments).join('\n')}`;
  console.log(req);
  // url hardcoded for test purposes
  const result = await request(`http://localhost:4466/news-mysql-prisma/local`, req, {lang: ctx.lang});
  return result.map(entry => collapseArticle(entry));
}

I run a query:

query {
  articlesLocalized {
    id
    publishedAt
  }
}

And it results in error:

{
  "data": null,
  "errors": [
    {
      "message": "Field 'type' of type 'Type' must have a sub selection. (line 11, column 3):\n  type\n  ^: {\"response\":{\"data\":null,\"errors\":[{\"message\":\"Field 'type' of type 'Type' must have a sub selection. (line 11, column 3):\\n  type\\n  ^\",\"locations\":[{\"line\":11,\"column\":3}]}],\"status\":200},\"request\":{\"query\":\"query($lang: String!) { articles {\\n  ...ArticleFlat \\n  translations(where: {lang: $lang}, first: 1) { ...ArticleTranslationFlat }\\n  type {...TypeFlat label(where: {lang: $lang}, first: 1) {...TypeLabelFlat}}\\n  tags {...TagFlat label(where: {lang: $lang}, first: 1) {...TagLabelFlat}}\\n} } fragment ArticleFlat on Article {\\n  id\\n  createdAt\\n  updatedAt\\n  publishedAt\\n  type\\n  status\\n}\\nfragment ArticleTranslationFlat on ArticleTranslation {\\n  lang\\n  title\\n  body\\n}\\nfragment TagFlat on Tag {\\n  id\\n  createdAt\\n  updatedAt\\n  color\\n  name\\n}\\nfragment TagLabelFlat on TagLabel {\\n  lang\\n  label\\n}\\nfragment TypeFlat on Type {\\n  id\\n  createdAt\\n  updatedAt\\n  color\\n  name\\n}\\nfragment TypeLabelFlat on TypeLabel {\\n  lang\\n  label\\n}\",\"variables\":{}}}",
      "locations": [
        {
          "line": 12,
          "column": 3
        }
      ],
      "path": [
        "articlesLocalized"
      ]
    }
  ]
}

BUT I copy the entire request from console and run it (the same request) directly over the same host, and it works:

2018-06-02 20 02 17

Request contents:

query($lang: String!) { articles {
  ...ArticleFlat 
  translations(where: {lang: $lang}, first: 1) { ...ArticleTranslationFlat }
  type {...TypeFlat label(where: {lang: $lang}, first: 1) {...TypeLabelFlat}}
  tags {...TagFlat label(where: {lang: $lang}, first: 1) {...TagLabelFlat}}
} } fragment ArticleFlat on Article {
  id
  createdAt
  updatedAt
  publishedAt
  type {
    id
  }
  status
}
fragment ArticleTranslationFlat on ArticleTranslation {
  lang
  title
  body
}
fragment TagFlat on Tag {
  id
  createdAt
  updatedAt
  color
  name
}
fragment TagLabelFlat on TagLabel {
  lang
  label
}
fragment TypeFlat on Type {
  id
  createdAt
  updatedAt
  color
  name
}
fragment TypeLabelFlat on TypeLabel {
  lang
  label
}

Problem: realFetch.call is not a function

Hi All,

I'm using graphql-request to connect from my lambda function to Graph.cool service.
My code works local without problem but when deployed on Lambda there is following error:

TypeError: realFetch.call is not a function
    at Object.fetch (/var/task/src/functions/webpack:/node_modules/cross-fetch/dist/node-ponyfill.js:9:1)
    at GraphQLClient.<anonymous> (/var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:105:1)
    at step (/var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:40:1)
    at Object.next (/var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:21:45)
    at /var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:15:1
    at new Promise (<anonymous>)
    at __awaiter (/var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:11:1)
    at GraphQLClient.request (/var/task/src/functions/webpack:/node_modules/graphql-request/dist/src/index.js:95:1)
    at updatedDb (/var/task/src/functions/webpack:/src/utils/updateDb.js:55:41)
    at loader.getJobs.map.e (/var/task/src/functions/webpack:/src/functions/fetch.js:17:50)
(node:1) UnhandledPromiseRejectionWarning: Error: TypeError: realFetch.call is not a function
    at Promise.all.then.catch.err (/var/task/src/functions/webpack:/src/functions/fetch.js:22:17)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)

My code is transpiled by webpack but it's obvious the there is some problem with cross-fetch dependency of graphql-request: /node_modules/cross-fetch/dist/node-ponyfill.js:9:1.

Could you plese help me? I don't know how to solve that issue.

How to return http status

Is it possible to return the http status code of the request? using:

request('http://localhost:3000', query)
        .then(data => console.log(**data.status**))

Only outputs 'undefined'?

Support for "GET" requests

Can you add "get" requests support? It's good for caching and it's not always necessary to use "post" requests.

Intercept every request

Hi there,

Is there a way how to intercept every request call?
For example in case response contains errors I want to deal with them in generic way.

thanks

Allow passing more options to fetch

First, thank you for the awesome work!

Currently the library seems to be only pass the headers option to fetch whilst fetch takes many more options like

fetch('https://example.com', {
  credentials: 'include'  
})

I'm not that familiar with typescript to make a quick pull request without messing things up, but perhaps keeping all the passed in options at https://github.com/graphcool/graphql-request/blob/master/src/index.ts#L18 and something like

const response = await fetch(this.url, Object.assign({}, this.options, {
      method: 'POST',
      headers: Object.assign({'Content-Type': 'application/json'}, this.options.headers),
      body,
    }))

at https://github.com/graphcool/graphql-request/blob/master/src/index.ts#L30.

Subscriptions Support

Hello,

It could be interesting to add the ability to subscribe to GraphQL events.

Thank you.

Usage in Typescript requires "dom" lib in tsconfig.json

@RomanGotsiy recently updated some dependencies resulting in Typescript projects using graphql-request having to add the dom lib to the tsconfig.json file.

We should somehow bake this into this library to facilitate usage with Typescript.

Any thoughts @RomanGotsiy?

cookie support

hey,

i am trying to use couple of GraphQLClients in a script used to send graphql requests with different login types. however, the GraphQLClient not supporting cookies or returning back the headers of the original request.
what do you think about adding cookies support (with isolated store) per client?

Server side rendering issue.

How it can be used with server side rendering(React + Redux)? require(cross-fetch/polyfill) in graphql-request creates an issue(trying to call fetch of undefined) during the build of server side bundle. I'm using webpack. Thank you.

Function returns undefined when query is malformed

Type: Bug

Steps:
Invoke the request function with the query with extra brackets: Note: the root level '{}' are added around the mutation statement

const mutation = `{
 mutation signinUser($email: String!, $password: String!) {
   signinUser(email: { email: $email, password: $password }) {
     token,
     user {
       id
     }
   }
 }
}`
const variables = {
     email: "some@email",
     password: "12345"
   }
request("..url..", mutation, variables).then(data => {
    console.log(data);
}).catch(err => {
    console.log(err)
});

Exepcted Result:
The 'catch' function should have been invoked with an error message stating that the query/mutation is malformed (or to the effect)

Actual Result
The result of 'data' comes through as 'undefined'

How can get the headers on response ?

I was playing with dist/src/index.js

Why return response.data instead response?
i'm trying to get the headers on the response, but when return response.data, i can't access to headers methods u.u.

maybe in the future?

Compatibility mode for older browsers/runtimes

Some people (#18, #16) have problems running graphql-request in older browsers or environments that don't support fetch or promises.

It would be great if we could introduce a compatibility mode (that additionally includes polyfils). This way graphql-request stays lean for the majority of use cases.

Two bugs in 1.7.0 due to including graphql dependency.

This is copy/pasted from a reproduction repository you can checkout :)

graphql-request-1.7.0-bug

This is a reproduction of a bug that came up in 1.7.0.

There are actually 2 bugs IMO.

Bundle Size

In 1.7.0, graphql-tag was added as a dependency and graphql was added to peerDependencies. One of the reasons we use graphql-request is because it's so small.

Here's the webpack output for [email protected]:

Hash: 00ae46853441bb94f0bc
Version: webpack 4.16.2
Time: 637ms
Built at: 2018-07-24 16:55:50
  Asset      Size  Chunks             Chunk Names
main.js  12.6 KiB       0  [emitted]  main
Entrypoint main = main.js
[1] ./src/index.js 25 bytes {0} [built]
    + 3 hidden modules

Here's the webpack output for [email protected]:

Hash: 7489bc885808f855eac6
Version: webpack 4.16.2
Time: 2910ms
Built at: 2018-07-24 16:54:42
  Asset     Size  Chunks             Chunk Names
main.js  156 KiB       0  [emitted]  main
Entrypoint main = main.js
[2] ./src/index.js 25 bytes {0} [built]
[5] ./node_modules/graphql/index.mjs + 99 modules 474 KiB {0} [built]
    |    100 modules
    + 4 hidden modules

Notice the difference in the main.js filesize: 12.6 KiB before, 156 KiB after. And this is using webpack --mode production. This is definitely a bug.

You can also checkout the built files:

webpack not handling a require statement

I'm honestly not sure what's up here, but if you open up the index.html in 1.6.0 and open the console there's nothing in there and the code in graphql-request runs fine.

If you open up the index.html in 1.7.0 there's the following error in the console:

main.js:1 Uncaught ReferenceError: require is not defined
    at Object.<anonymous> (main.js:1)
    at t (main.js:1)
    at Module.<anonymous> (main.js:1)
    at t (main.js:1)
    at Object.<anonymous> (main.js:1)
    at t (main.js:1)
    at Module.<anonymous> (main.js:1)
    at t (main.js:1)
    at main.js:1
    at main.js:1

I'm not 100% certain why that's happening, but it's this statement:

require("./../../process/browser.js");

I think it's in the graphql/jsutils/instanceOf.mjs file where it's using process. I'm not sure why that's causing issues here...

That said, if the first bug is fixed (remove the dependency on graphql), then this bug will also be fixed.

Thanks!

Replace isomorphic-fetch with node-fetch

Given problems as describe in #14 it probably makes sense to replace isomorphic-fetch with node-fetch.

Let's keep this up for discussion for a while to collect feedback/hear objections.

Instructions for getting graphql-request to work with IE10/11

Hi!

I'm using graphql-request for a small app which now (sadly) has to support IE10 and IE11.

I used several obvious polyfills (es6-promise, es6-object-assign etc.) but couldn't get requests and their handling to fully work. That's why I ended up using babel-polyfill which handles applying needed polyfills automatically.

As it bloats the resulting JS with a lot of possibly unneeded polyfills I wanted to ask you guys if you could provide a list of needed polyfills for IE10 and IE11 which could be added to the docs.

Thanks in advance.

Exception when result.errors is an empty array

In index.ts:request the following code checks if result.errors is undefined:

    if (response.ok && !result.errors && result.data) {
      return result.data
    } else {
      const errorResult =
        typeof result === 'string' ? { error: result } : result
      throw new ClientError(
        { ...errorResult, status: response.status },
        { query, variables },
      )
    }

My code looks pretty much like the example in the README:

const { request } = require('graphql-request')

const query = `{
  typeOne(ids:["13442595"]) {
    typeTwo{
        id
        name 
      }
    }
  }`;

request('https://api-endpoint/graphql', query)
  .then(data => console.log(data))
  .catch(err => console.log(err))

The response contains result.errors as an empty array which has a truthy value. The above if-statement then evaluates to false, leading to the ClientException being thrown, albeit with the expected data still in the response.

Changing if (response.ok && !result.errors && result.data) to if (response.ok && !result.errors.length && result.data) fixes the issue, but I'm not sure if it's a sustainable solution.

Node version: 9.4.0

Request batching support

If a PR were submitted for basic request batching (possibly query deduping) would it fit into the goals of this project?

Extensions

What are the thoughts on including the response.extensions key in the returned result?

Extensions are defined in the GraphQL spec:

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

To ensure future changes to the protocol do not break existing servers and clients, the top level response map must not contain any entries other than the three described above.

This would probably require a breaking change to this code: https://github.com/graphcool/graphql-request/blob/master/src/index.ts#L34-L44

Cross fetch Sanitization of header leads to error

jest-html-reporter >> Error: Invalid character (☺) in string: TypeError: ___utmvaMzuZKyc=hWA☺GqrM; path=/; Max-Age=900 is not a legal HTTP header value.

When updated from 1.6.0 to 1.8.1, this leads to error.
Can anyone investigate the same?

`src/index.ts` Cannot be found with by webpack dev server

Hi, I really like this package but recently I ran into a problem in a TypeScript project:

Hot reloading does not work well. I don't have this problem for other packages like typeorm which also provides it's own type definitions.

17:13:28 webpack.1    | (Emitted value instead of an instance of Error) Cannot find source file '../../src/index.ts': Error: Can't resolve '../../src/index.ts' in '/Users/me/project/node_modules/graphql-request/dist/src'
17:13:28 webpack.1    |  @ ./client/components/orgs.tsx 2:0-42 23:8-15
17:13:28 webpack.1    |  @ ./client/components/client.tsx
17:13:28 webpack.1    |  @ ./client/index.tsx
17:13:28 webpack.1    |  @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server babel-polyfill ./client/index.tsx
17:13:28 webpack.1    |

For some reason it's traversing 2 directories up and then failing to find that file.

[Discussion] Better error handling

Error handling is currently not ideal and I'd love to hear ideas how to handle errors in a better way.

This is the current way:

import { request } from 'graphql-request'

const wrongQuery = `{
  some random stuff
}`

request('my-endpoint', query)
  .then(data => console.log(data))
  .catch(err => {
    console.log(err.response.errors) // GraphQL response errors
    console.log(err.response.data) // Response data if available
  })

The implementation can be found here.

Optional cross-fetch a.k.a. should libs include polyfills?

I'm really liking this projects simple aproach and small filesize. 80% of the time I have no need for a full-fledged client-side GraphQL framework so it's a great fit for most projects.

My only gripe is the included cross-fetch fetch polyfill. I'm of the school of thought that libraries should not include any polyfills and instead leave that up to the end developer. This prevents duplication of conflicting polyfills and gives the fexibility to swap out polyfill solutions as necessary. For modern/internal projects it's often not even necessary to use polyfills so it can avoid the performance penatlties of needing to parse the JS on load.

I'd like to propose removing cross-fetch and instead giving clear instructions in the documention about including a polyfill if legacy browser or node support is necessary.

Request "query" is sent with unnecessary spaces

The request payload includes unnecessary whitespace characters in the query.

Current result

For example, when requesting this query:

{
  user {
    id
    name
    email
  }
}

inspecting the fetch request you would see (note the spaces and unnecessary \n):

query: '{\n  user {\n    id\n    name\n    email\n  }\n}'

Expected result

It would be nice if superflous whitespace was trimmed to save bytes:

query: '{user{id\nname\nemail}}'

This might get tricky when dealing with args, variables, etc. Also worth noting that gzip mitigates some of the bytes from repeated characters but obviously not including those characters in the first place will yeild even better byte savings.

This could be implemented external to graphql-request in each developers app but it feels like something that should be part of the core package.

Graphql-request return error data

I use graphql-request first time. I send query request, server return correct response. Like this:

{"data":{"alldeployservice":[{"mid":"5ab4b33ff648b52ebe3ebb33","name":"eqxiu-vip-web"},{"mid":"5ab4b340f648b52ebe3ebb34","name":"demo-a"},{"mid":"5ab4b340f648b52ebe3ebb35","name":"demo-b"},.......{"mid":"5ac9774b80d9f04c7cfa7a7c","name":"eqxiu-open-web"}]}}

But graphql-request tell me the server return error data.

Error: Error: GraphQL Error (Code: 200): {"response":{"error":"{\"data\":{\"alldeployservice\":[{\"mid\":\"5ab4b33ff648b52ebe3ebb33\",
..........
{\"mid\":\"5ac9774b80d9f04c7cfa7a7c\",\"name\":\"eqxiu-open-web\"}]}}\n","status":200},"request":{"query":"{\n    alldeployservice {\n      name\n      mid\n    }\n}"}}

This is my code

import {GraphQLClient} from 'graphql-request'
const queryAllDeployServices = `{
    alldeployservice {
      name
      mid
    }
}`
export async function queryAllDeployService() {
  const client = new GraphQLClient("http://192.168.1.33:8000/api")
  return client.request(queryAllDeployServices).then(res=>console.log(res))
}

I don't know how to fix this issue...
Can everyone help me?
Tks!

Failing requests

I tried sending requests to Yelp's GraphQl API from the library. Although they worked perfectly fine in postman, they were failing for some reason in my react-native app.

A typical request in the app,

const client = new GraphQLClient('https://api.yelp.com/v3/graphql', {
  headers: {
    Authorization: `Bearer ACCESS_TOKEN`,
    'Content-Type': 'application/graphql',
    'Accept-Language': 'en_US',
  },
});
const query = `{
  search(term:"free wifi",latitude:37.785834,longitude:-122.406417,limit: 10) {
    total
  }
}`
client.request(query).then(data => console.log(data)).catch(e => console.log(e));

The above request resulted in an error with the following error message, The server has either erred or is incapable of performing the requested operation.

The same request worked with postman.

screen shot 2017-08-24 at 8 58 22 pm

screen shot 2017-08-24 at 8 58 11 pm

After looking at the source code, I found out that the way in which the the body variable was declared was the issue. The requests started returning data after defining the variable in the following way,
const body = query

Any thoughts on this?

Support for parsed queries (AST)

If you use graphql-tag, you need to print() your queries when passing them to graphql-request. It would be helpful if you could pass in those AST queries directly.

modules

Am I right in thinking the only way to use this is with webpack as it uses import {request} ?
For something claiming to be super-simple, you shouldn't make assumptions about other peoples build chains.

HTTPS broken in Node 8 & 9

I tried to handle this in downstream node-fetch, but they pointed out that the issue needs to be solved in upstream.

I am not going to bother you with details you can find in links. However, there is one issue to discuss in here. There is basically a need to be able to create https.Agent with { ecdhCurve: auto } and pass it to fetch call. However, if I am not mistaken https.Agent is not exactly a cross-platform. Am I missing something in here?

I noticed the issue #41 by @kbrandwijk that might be related, but probably not that much.

Reliably check bundle size in CI to avoid any size regression

While implementing this #10, we inadvertently increased the size of this package beyond 150KB (minified and tree-shaken), and based on the discussion/attempts in #94 we noticed that bundlesize and bundlephobia didn't reliably detect the increased package size, maybe because of it being a peer dependency.

We should find measures to reliably detect package size in CI.

Add a mutate function

I tried your lib today, but then ran into the issue that it only allows to run queries. Would be cool to send mutations as well or maybe as a separate lib.

Changelog

Hi! Thanks for the great plugin!

What I'm missing in the project is a changelog. Example: I could not really figure out if and when #9 made it into a release.

Could you either add a release description mentioning changes that made it into a release in https://github.com/graphcool/graphql-request/releases or provide a CHANGELOG.md file in the project with that information?

Cannot add `agent` to Options

The agent field is missing in Options. However, if I try to add it, Typescript won't compile, because it says it's not a part of RequestInit. This is because @types/node-fetch and @types/whatwg-fetch have a different interface definition for RequestInit. Only the node-fetch one includes agent.

I have no idea how to fix this.

Using isomporhic-fetch causes error in ReactNative

Just had this issue when I got the latest graphql-request and it was hard to track down. After finding similar issues it seems to be that graphql-request is now using isomophic-fetch which in a react native build fails:

Can't find variable: self

http://imgur.com/PzHkGC6

Issues reported:

It also looks like that the libarary is not well supported. It was last published 2 years ago and a number of PRs are outstanding... even one that resolves this issue.

Not sure if it would be a solution to move away from this libarary but in its current for I cannot use this within my app.

how to set header every request?

In apolloclient, I can do it like this:

import { ApolloClient, createNetworkInterface } from 'react-apollo';
const networkInterface = createNetworkInterface({
  uri: '/graphql',
});
networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    // get the authentication token from local storage if it exists
    const token = localStorage.getItem('token');
    req.options.headers.authorization = token ? `Bearer ${token}` : null;
    next();
  }
}]);
const client = new ApolloClient({
  networkInterface,
});

How can I do it in gql-request?

Thanks.

Differences to graphql-fetch?

What are the differences between this package and the existing graphql-fetch by @tjmehta? It looks like this package duplicates a lot of the functionality in graphql-fetch.

Support using Docker service hostnames

Currently I am trying to use this in a Node.js app inside Docker, which needs to connect to another Docker container which is running my GraphQL endpoint.

Normally you would just use the Docker service name so that Docker's internal DNS resolves it transparently, however this is not possible here because an error gets thrown (seemingly from an underlying dependency, perhaps isomorphic-fetch):

Error: only absolute urls are supported

Support for query batching

Some GraphQL servers, such as Graphcool, allow the client to batch multiple queries/mutations into one HTTP request by sending an array of GraphQL request objects ({ query, variables }) in the request body.

Given the current implementation I can see two ways of doing this:

  1. Modify GraphQLClient.request to accept both standard arguments (query, variables) and an array of request objects
  2. Create a new method (something like GraphQLClient.batchRequest) that only accepts an array of request objects

I'd be interested to see how error handling would work for batch requests - would an error be thrown for the whole batch request if any one of its child queries/mutations returned an error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.