GithubHelp home page GithubHelp logo

apollographql / apollo-fetch Goto Github PK

View Code? Open in Web Editor NEW
571.0 571.0 32.0 219 KB

:dog: Lightweight GraphQL client that supports middleware and afterware

Home Page: https://www.npmjs.com/package/apollo-fetch

License: MIT License

TypeScript 98.87% JavaScript 1.13%
apollo fetch graphql graphql-client http

apollo-fetch's People

Contributors

ctavan avatar helfer avatar jaydenseric avatar kamilkisiela avatar lquixada avatar renovate-bot avatar renovate[bot] avatar tuxsudo 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  avatar  avatar  avatar  avatar  avatar  avatar

apollo-fetch's Issues

Network request failed. Payload is not serializable: Converting circular structure to JSON

using createaApolloFetch() to merge schemas I am having Network request failed. Payload is not serializable: Converting circular structure to JSON error and I don't know if I am doing something wrong, this is my piece of code:

const remoteUrl = "http://my_url/graphql";
const fetcher = createApolloFetch({ uri: remoteUrl });
fetcher.use(({ request, options }, next) => {
    options.headers = {
        'Authorization': "token"
    };

    next();
});
return makeRemoteExecutableSchema({
    schema: await introspectSchema(fetcher),
    fetcher
});

}

export const schema = remoteExecutableSchema();`

This is the error I am getting:
Error: Network request failed. Payload is not serializable: Converting circular structure to JSON at Object.checkResultAndHandleErrors ...node_modules/graphql-tools/dist/stitching/errors.js:69:36) at Object.<anonymous> (/.../node_modules/graphql-tools/dist/stitching/delegateToSchema.js:92:52) at step (.../node_modules/graphql-tools/dist/stitching/delegateToSchema.js:40:23) at Object.next (.../node_modules/graphql-tools/dist/stitching/delegateToSchema.js:21:53) at fulfilled (.../node_modules/graphql-tools/dist/stitching/delegateToSchema.js:12:58) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)

Feature: File upload?

I think apollo-fetch has an opportunity to be the only simple GraphQL client library out there with support for file uploads. Looks like apollo-upload-client is quite simple implementation-wise, so it would be fine to build that stuff right in!

@jaydenseric @evanshauser @jbaxleyiii let's talk here, I think this would be a big win not only for Apollo Client having file upload capability, but also for apollo-fetch as a standalone utility!

Apollo Client 2.0 usage

Apollo Client 2.0 requires a link option which is in conflict with setting the uri on createApolloFetch. Does this imply that apollo-fetch is now legacy for use with pre 2.0 clients?

What's the advantage of afterware vs. middleware?

Middleware could easily function before/after a request:

const middleware = (req, options, next) => {
  options.headers = options.headers || {};
  options.headers['authorization'] = 'created token';
  return next(req, options);
};

const afterware = (req, opts, next) => {
  const res = next(req, opts);
  if (401 === res.status) {
    logout();
  }
  return res;
};

Is there a reason to have explicit middle/after stacks that I'm not seeing?

self.fetch.bind(self) not defined in the browserified js file

I created a node.js file called fetch.js having graphQL call using apollo-fetch. When i run it without browserifying, like, node fetch.js , i get the intended outcome as

returned from custom test function

After i browserified it and created bundle.js and when i try to run the browserified file , i am getting the error

fetch not defined

Then i included es6-promise and isomorphic-fetch, after looking at the related bugs, and now i am getting the error

self.fetch.bind(self) not defined

Please find below my fetch.js, schema and resolver files

`
require('es6-promise').polyfill();
var fetch=require('isomorphic-fetch').fetch;

const { createApolloFetch } = require('apollo-fetch');
const fetchQL = createApolloFetch({
uri: 'http://localhost:4000/graphql',
});

fetchQL({
query: '{testFunction}',
}).then(res => {
console.log(res.data.testFunction);
});
`

with schema as
type myQuery { testFunction: String! }

and resolver as
myQuery:{ testFunction(){ return "returned from custom test function"; }

Can you return error from middleware to client?

Let's say I request a mutation and it happens that I'm authenticated but not authorized in terms of my user type to write to the resource (this means that, assuming we can find out if the user is authenticated, we would lookup the userid from the JWT token or something like that and find out if user is authorized (by comparing user role in db to some value(s) and if not then it would return an error that comes back to client in the mutation result? Is that possible. I'm current using FeathersJS 'before' hooks to do this.

Make the package look more lightweight

This is feedback from @tmeasday - the readme makes this package look like it's doing a lot more than just a fetch, when in fact we want it to be a super thin wrapper. Let's update the readme/description to make people feel better about using it.

TypeScript Compile Type Error while calling introspectSchema with 'apollo-fetch'

#I'm Trying to create a remote Schema and Im doing it like this:

import {makeRemoteExecutableSchema, introspectSchema} from 'graphql-tools';
import {createApolloFetch} from 'apollo-fetch';
const fetcher = createApolloFetch({uri: this.uri});
        return makeRemoteExecutableSchema({
            schema: await introspectSchema(fetcher),
            fetcher
        });

and I'm getting this error when I try to run my project

TSError: β¨― Unable to compile TypeScript
2|SMALA-Ga | server/graphql/proxy/index.ts (18,43): Argument of type '{ schema: any; fetcher: ApolloFetch; }' is not assignable to parameter of type '{ schema: string | GraphQLSchema; link?: ApolloLink; fetcher?: Fetcher; }'.
2|SMALA-Ga | Types of property 'fetcher' are incompatible.
2|SMALA-Ga | Type 'ApolloFetch' is not assignable to type 'Fetcher'. (2345)

the message of the error is clear so when we check accepted parameters by introspectSchema we find ApolloLink | Fetcher only :

export default function introspectSchema(fetcher: ApolloLink | Fetcher, linkContext?: {
    [key: string]: any;
}): Promise<GraphQLSchema>;

but ApolloFetch which is the return type of createApolloFetch is not accepted
export declare function createApolloFetch(params?: FetchOptions): ApolloFetch;

well this issue can be fixed by changing the fetch to ApolloLink for example but personally, I like ApolloFetch due it's flexibility on changing the request parameters --> I mean something like this:

const fetcher = createApolloFetch({uri: this.uri});
        fetcher.use(({ request, options }, next) => {
            if(context.req.get('authorization')) {
                if (!options.headers) {
                    options.headers = {};
                }
                options.headers['Authorization'] = context.req.get('authorization');
                next();
            }

I'm Using TypeScript with ts-node

ts-node v6.0.0
node v9.5.0
typescript v2.8.1

I'm not really sure about supporting typescript in Apollo because I found other typing issues that I will report them in different threads.

Error : Unexpected token < in JSON

I'm able to run the query successfully and gets valid JSON data in GraphQL Editor. But when I use apollo-fetch , the server returns html instead of json. Hence I get the error "Unexpected token <" . I don't understand why the server returns html response instead of json. I'm using this code

const {createApolloFetch} = require('apollo-fetch')
const uri = 'http://mygraphqlserver:6989/graphiql'
const data = {
  getnewAppsCount: async () => {
    const query = `query TestQuery($startDate: String!, $endDate: String!, $sortDir: Int, $statusCodes: [String]!) {
        newappsCount(filter: {startDate: $startDate, endDate: $endDate, statusCode: $statusCodes, sortDir: $sortDir, skip: 0, take: 10}) {
          count
          submittedDate
          applicationStatus
        }
      }
      `
    const variables = {
      'startDate': '01-Jul-2017',
      'endDate': '31-Aug-2017',
      'sortDir': -1,
      'statusCodes': [
        '200.01'
      ]
    }
    try {
      const apolloFetch = createApolloFetch({ uri })
      let data = await apolloFetch({ query, variables })
        // console.log(data)
      return data
    } catch (error) {
      console.log(error)
    }
  }
}
module.exports = data

I'm using apollo graphql with nodejs on the server side, and it works fine in graphql editor.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

ReactNativeFile alternative if not using ReactNative

Hi,

It seems that the File API is not available in NativeScript (using it with a Vue app), which makes uploading files difficult since there is no 'File' ( [ReferenceError: File is not defined] )
Is there an alternative work around? (In the meantime I think I'll do a base64 encoding, but that's not ideal).

Much appreciated!

Maximum call stack size exceeded

I use "apollo-fetch": "^0.7.0",use apolloFetch as koa2's middlewares,running in Kubernetes for some hours,something go wrong,these are logs:
Maximum call stack size exceeded
at next (/home/node/code/node_modules/_apollo-fetch@0.7.0@apollo-fetch/dist/bundle.umd.js:17:25)
at apolloFetch.use (/home/node/code/src/middlewares/apolloFetch.js:13:5)
at next (/home/node/code/node_modules/_apollo-fetch@0.7.0@apollo-fetch/dist/bundle.umd.js:21:19)
at apolloFetch.use (/home/node/code/src/middlewares/apolloFetch.js:13:5)
at next (/home/node/code/node_modules/_apollo-fetch@0.7.0@apollo-fetch/dist/bundle.umd.js:21:19)
at apolloFetch.use (/home/node/code/src/middlewares/apolloFetch.js:13:5)
at next (/home/node/code/node_modules/_apollo-fetch@0.7.0@apollo-fetch/dist/bundle.umd.js:21:19)
at apolloFetch.use (/home/node/code/src/middlewares/apolloFetch.js:13:5)
at next (/home/node/code/node_modules/_apollo-fetch@0.7.0@apollo-fetch/dist/bundle.umd.js:21:19)
at apolloFetch.use (/home/node/code/src/middlewares/apolloFetch.js:13:5)

some code is:
apolloFetch.use(({ options }, next) => {
if (!options.headers) {
options.headers = {}
}
options.headers['Authorization'] = token
next()
})

ctx.apolloFetch = apolloFetch

await next();

Can custom fetch be the default behavior

Howdy! Long time user of the apollo graphql tools. This library hits a lot of good notes, and was able to use it instead of a home grown solution, due to the API being small and plugable.

Would it be possible to not include isomorphic-fetch by default, and have that be the custom option?

I am using a different fetch implementation, and I would like to not include isomorphic-fetch at all if possible.

Default behavior would be to use native browser fetch. If a custom fetch is needed (which would be yes in my case), then you still have the customFetch property. For users who need isomorphic fetch, they could also use the customFetch property.

Unable to override Apollo Client's default content-type 'application/json' header

@jbaxleyiii great meeting you at the GraphQL NYC meetup last night! Really enjoyed yours and Sashko's talks on the innovation within the Apollo + GraphQL ecosystem - this schema stitching (local+remote, remote+remote) stuff is wild and exciting.

We chatted briefly yesterday about the issue I was having with overriding the default content-type application/json header that is set by Apollo Client. If you have any thoughts on the best way to resolve this, let me know! I'm happy to contribute back a PR to extend the client's flexibility

Intended outcome:

Additional context here: Yelp/yelp-fusion#278 (comment)

I'm attempting to make a request to the Yelp GraphQL API server by setting a content-type header of application/graphql (as suggested by the Yelp GraphQL docs for sending raw GraphQL queries, https://www.yelp.com/developers/graphql/guides/requests)

const networkInterface = createNetworkInterface({
  uri: 'https://api.yelp.com/v3/graphql',
});

networkInterface.use([
  {
    applyMiddleware(req, next) {
      if (!req.options.headers) {
        req.options.headers = {}; // Create the header object if needed.
      }

      req.options.headers.authorization = yelpAccessToken ? `Bearer ${yelpAccessToken}` : null;
      req.options.headers['content-type'] = 'application/graphql';
      req.options.headers['accept-language'] = 'en_US';
      next();
    },
  },
]);

const client = new ApolloClient({
  networkInterface,
});

query

const RestaurantListingQuery = gql`
  query {
    business(id: "garaje-san-francisco") {
      name
      id
      location {
        city
      }
    }
  }
`;

Expected Result: response from Yelp GraphQL API with valid restaurant data

{
    "data": {
        "business": {
            "name": "Garaje",
            "id": "garaje-san-francisco",
            "rating": 4.5,
            "url": "https://www.yelp.com/biz/garaje-san-francisco?adjust_creative=x7LWoNv05Hf_vNeFecFImQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_graphql&utm_source=x7LWoNv05Hf_vNeFecFImQ"
        }
    }
}

Actual outcome:

Instead of overriding the default content-type: application/json header, the Apollo client appears to prepend application/json to the specified application/graphql value. This results in a concatenated content-type: application/json, application/graphql header.

screen shot 2017-08-14 at 8 27 57 pm

The result of this request is a malformed content-type header, to which the Yelp GraphQL API responds with Must provide query string.

Other observations

In Postman,

  • the Yelp GraphQL API responds with the expected data if content-type: application/graphql set

screen shot 2017-08-12 at 12 28 59 pm

  • the Yelp GraphQL responds with "Must provide query string" error if content-type: application/json, application/graphql set

screen shot 2017-08-14 at 7 43 09 pm

Version

Readme example doesn't typecheck

Intended outcome:

The middleware example in the readme should typecheck when used in Typescript:

apolloFetch.use(({ request, options }, next) => {
  if (!options.headers) {
    options.headers = {};  // Create the headers object if needed.
  }
  options.headers['authorization'] = 'created token';

  next();
});

Actual outcome:

An empty object cannot be assigned to options.headers:

message: 'Type '{}' is not assignable to type 'Headers | string[][] | undefined'.
  Type '{}' is not assignable to type 'string[][]'.
    Property 'includes' is missing in type '{}'.'

Apparently options.headers is either string[][] or Headers, where Headers seems to be (from the dom lib in the Typescript compiler options below):

interface Headers {
    append(name: string, value: string): void;
    delete(name: string): void;
    forEach(callback: ForEachCallback): void;
    get(name: string): string | null;
    has(name: string): boolean;
    set(name: string, value: string): void;
}

How to reproduce the issue:

Typescript compiler options:

{
  "compilerOptions": {
    "outDir": "./dist",
    "allowJs": true,
    "target": "es2017",
    "module": "commonjs",
    "lib": ["esnext", "esnext.asynciterable", "es2017", "dom"],
    "noUnusedLocals": true,
    "noErrorTruncation": true,
    "strict": true
  }
}

If there's anything else you need to be able to reproduce, let me know and I'll try to help out.

[feature idea] graphql-tag support.

I'm using apollo-fetch in my nodeJS server, to fetch data from my micro services which are also in graphql.

-- works fine. Thank you.

but the thing is that graphql-tag suppose to let us use fragments + let us use plugins which allow auto complete for fields and fragments. (which is EXTREMELY helpful in our huge schemas).

apollo client support it, so I though apollo-fetch would support it too, but I when I try to use apollo-fetch with graphql-tag - I get invalid json response from the microservice. (Java GraphQL).
without graphql - works great, but doesn't let me use very helpful features.

Thank you !

example :
works :

    const query = `
  query CurrentUser {
    currentUser {
      login,
    }
  }
`

doesn't work :

 import gql from 'graphql-tag';
 
 const query = gql`
  query CurrentUser {
    currentUser {
      login,
    }
  }
`

(Or is the java server responsibility? maybe I need to add him a tool to parse ast ?)

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.