apollographql / apollo-fetch Goto Github PK
View Code? Open in Web Editor NEW:dog: Lightweight GraphQL client that supports middleware and afterware
Home Page: https://www.npmjs.com/package/apollo-fetch
License: MIT License
:dog: Lightweight GraphQL client that supports middleware and afterware
Home Page: https://www.npmjs.com/package/apollo-fetch
License: MIT License
For backends that verify that the request only has query
, variables
, and operationName
, Apollo Fetch passes on every field in the request by default (including the context
), which might cause failures to resolve on the backend.
This is the case with the Optics backend :D
cc: @jbaxleyiii
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?
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.
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!
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.
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.
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)
Following my reasoning in apollographql/apollo-client#2008 I think it would be a good practice if a library like apollo-fetch
did not modify the global namespace by polyfilling fetch
.
Is there any particular reason not to use https://github.com/qubyte/fetch-ponyfill instead? If you would accept a ponyfill instead of a polyfill I'd be happy to contribute a PR.
Bundle-size wise there should be no signifcant difference.
@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.
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,
content-type: application/graphql
setcontent-type: application/json, application/graphql
setVersion
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.
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();
Any thought to using a speedier JSON stringifier than the native JSON.stringify()
?
E.g.: fast-stable-stringify, fast-json-stable-stringify, or fast-json-stringify?
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?
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.
I'm seeing this error whenever I use apollo-fetch
in react native.
This is likely caused by matthew-andrews/isomorphic-fetch#125. Would really appreciate it if it can be resolved soon.
Related: apollographql/apollo-link#75
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 ?)
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"; }
Support of HTTP proxy (on backend services) is a critical component of a HTTP client.
It is a simple abstraction to implement using http(s)-proxy-agent
libraries, https://github.com/gajus/xfetch/blob/fe4b5a6c258fedc6d28f873368d7e06ea625b6bc/src/index.js#L99-L109.
#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.
π¨ 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.
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!
For this to work all we need to do is publish a UMD to npm, similar to what we have in Apollo Client!
Sorry if this is the wrong place to ask this. Will this library ever handle requests over websockets? This has supported full websocket transport for a couple months: https://github.com/apollographql/subscriptions-transport-ws#full-websocket-transport but I haven't found a way to use graphiql that way or anyone really supporting full websocket transport.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.