How to initialise an instance of `ApolloClient` in nodejs? - graphql

I have below code written in nodejs10.
const ApolloClient = require('apollo-boost');
const client = new ApolloClient({
uri: 'http://localhost:8000/graphql'
});
The error I got when running this program is:
const client = ApolloClient({
^
TypeError: ApolloClient is not a function
Below is the dependencies:
"apollo-boost": "^0.3.1",
"apollo-cache-inmemory": "^1.6.0",
"apollo-client": "^2.6.0",
"apollo-link-http": "^1.5.14",
"apollo-server": "^2.5.0",
"apollo-server-express": "^2.5.1",
I followed the user guide to setup a apollo client to take to me server. But it failed at very beginning stage. I wonder what wrong with my code. Is there anything I missed?

In order to initialize Apollo Client, you must specify link & cache properties on the config object. You can override this by using the default import.
const apollo = require('apollo-boost');
const ApolloClient = apollo.default;
const client = new ApolloClient({
uri: 'http://localhost:8000/graphql'
});

require('apollo-boost') does not return ApolloClient, it returns an object that contains ApolloClient.
From a github issue on ApolloGraphQL/apollo-client:
// es6 import
import { default as ApolloClient } from 'apollo-boost';
// es5 or Node.js
const Boost = require('apollo-boost');
const ApolloClient = Boost.DefaultClient;

Related

Single React JS project with multiple graphql URI Link

Hello I am new to ApolloClient and I don't know to pass multiple URI links as a clint and I have to use those all URI if anyone knows about it give me suggestions, what I have to do next.
import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from '#apollo/client';
// Set `RestLink` with your endpoint
const shopLink = new HttpLink({ uri: 'https://demo.vendure.io/shop-api' });
const cmsLink = new HttpLink({
uri: 'https://cms.trylah.sg/graphql',
});
const vendureLink = new HttpLink({
// Production
//uri: 'https://demo.trylah.sg/shop-api',
uri: process.env.REACT_APP_SHOP_API_URL || 'http://localhost:3000/shop-api',
credentials: 'include',
});
export const client = new ApolloClient({
link: shopLink,
cache: new InMemoryCache(),
});
I had a similar challenge and used
apollo-multi-endpoint-link to set Apollo Link to have an API directive to fetch data from multi endpoints.
You can see a working prototype in this repo for how I did it.
Hopefully that helps!

getInitialProps in never called in NextJS

I have problem with getInitialProps method in NextJS. It is never called. This is project where I have Apollo GraphQL client for some pages and getInitialProps for other. I am not sure how to configure them correctly to work.
Apollo is working fine and fetching data as it should. Problem is that getInitialProps isn't called.
Here is my custom _app.js file
const App = ({ Component, pageProps, apollo }) => {
return (
<ApolloProvider client={apollo}>
<Component {...pageProps} />
</ApolloProvider>
)
}
const API_URL =
process.env.NODE_ENV === "development"
? "http://localhost/wordpress/index.php?graphql"
: "https://page/index.php?graphql"
export default withApollo(({ initialState }) => {
return new ApolloClient({
link: new createHttpLink({
uri: API_URL,
fetch: fetch
}),
cache: new InMemoryCache()
})
})(App, { getDataFromTree })
And here is how I call getInitialProps on page
Coupons.getInitialProps = async function() {
const res = await fetch('http://localhost:8000/data/');
const data = await res.json();
console.log(`Data fetched. Count: ${data.length}`);
return {
shows: data.map(entry => entry.show)
};
};
Also. Pages where I have Apollo fetching data doesn't need to call this REST API. Apollo pages and REST pages are totally different
This problem was fixed by following documentation on https://github.com/zeit/next.js/tree/canary/examples/with-apollo
Thing is that I wrapped whole _app in Apollo provider and right way is to wrap only pages that need Apollo in it.
Other that need getInitialProps should remain as is and call REST API in them.

GraphQL react-apollo - is it okay to export/import client directly?

I have an apollo setup file, services/apollo.js, where I export the client:
const client = new ApolloClient({
cache,
link: ApolloLink.from([stateLink, httpLink])
})
export default client
and I then import that and use it as normal elsewhere:
<BrowserRouter>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</BrowserRouter>
If I want to use the client directly (for manually firing off a query for example), is it okay to import it directly into the file, rather than accessing it via ApolloConsumer?
import client from 'services/apollo'
export const getSomeData = async () => {
const { data } = await client.query({ ... })
console.log(data)
}
Yup, that should be fine.
This blog post mentions using a singleton for Apollo:
I use a singleton with a unique apollo client to keep a unique cache
and use in all code.
https://cheesecakelabs.com/blog/apollo-graphql-client-makes-api-integration-breeze/

Cannot read property 'startsWith' of undefined at Object.renderGraphiQL

i was going through a GraphQL tutorial from udemy,
https://www.udemy.com/introduction-to-graphql-and-apollo-building-modern-apis
And i was going through the guide to operating graphql and graphiql -> apollo -express - server. And got this. This particular error has not been defined in the videos. It is a free tutorial and lecture 9 has this.
Wht to do. i find no solution. Please help.
TypeError: Cannot read property 'startsWith' of undefined
at Object.renderGraphiQL (/home/dell/Desktop/graphql-
tutorial/node_modules/apollo-server-module-
graphiql/src/renderGraphiQL.ts:48:17)
at Object. (/home/dell/Desktop/graphql-tutorial/node_modules/apollo-
server-module-graphiql/src/resolveGraphiQLString.ts:62:10)
at step (/home/dell/Desktop/graphql-tutorial/node_modules/apollo-
server-module-graphiql/dist/resolveGraphiQLString.js:32:23)
at Object.next (/home/dell/Desktop/graphql-
tutorial/node_modules/apollo-server-module-
graphiql/dist/resolveGraphiQLString.js:13:53)
at fulfilled (/home/dell/Desktop/graphql-tutorial/node_modules/apollo-
server-module-graphiql/dist/resolveGraphiQLString.js:4:58)
at
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
renderGraphiQLString.js
This is the line it says has error -->
export function renderGraphiQL(data: GraphiQLData): string {
const endpointURL = data.endpointURL;
const endpointWs =
endpointURL.startsWith('ws://') || endpointURL.startsWith('wss://');
const subscriptionsEndpoint = data.subscriptionsEndpoint;
const usingHttp = !endpointWs;
const usingWs = endpointWs || !!subscriptionsEndpoint;
const endpointURLWs =
usingWs && (endpointWs ? endpointURL : subscriptionsEndpoint);
resolveGraphiQLString.js
export async function resolveGraphiQLString(
query: any = {},
options: GraphiQLData | Function,
...args
): Promise<string> {
const graphiqlParams = createGraphiQLParams(query);
const graphiqlOptions = await resolveGraphiQLOptions(options,
...args);
const graphiqlData = createGraphiQLData(graphiqlParams,
graphiqlOptions);
return renderGraphiQL(graphiqlData);
}
server.js
import express from 'express';
import {graphqlExpress,graphiqlExpress} from 'apollo-server-express';
import bodyParser from 'body-parser';
import schema from './schema.js'
const server = express();
server.use('/graphql', bodyParser.json(), graphqlExpress(schema));
server.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql'
}));
server.listen(4000,() =>{
console.log('listening on port 4000');
});
I was doing the same tutorial and got stuck with the same error. I just now got it working. For me, I had spelled endpointURL as endpointUrl because it seems stupid to me to capitalize acronyms within camel-case, but of course this being a specific key, it has to be spelled right.
For you, the only difference I see in the code is that I think you should pass {schema} to graphqlExpress, but you're passing just schema. So here's how I have it:
server.use("/graphql", bodyParser.json(), graphqlExpress({ schema }))
Your code is not correct. In order to define the graphiql endpoint you need to do this in the following way:
const server = express();
server.use('/graphql', bodyParser.json(), graphqlExpress(schema));
server.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
Keep in mind you should pass to the graphiqlExpress method the endpointURL of your real graphql endpoint.
Cheers!

How to properly setup flow to work with react-apollo?

I know that some initial flow typing were merged in apollo-client.
How can I use it?
Should I declare my own lib definitions? (I use flow-typed currently).
Could you please share an example of such definitions (particularly for react-apollo)?
For example, If I have such code:
// #flow
import { ApolloClient, createNetworkInterface } from 'react-apollo';
import fetch from 'isomorphic-fetch';
let apolloClient = null;
// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
global.fetch = fetch;
}
function create() {
return new ApolloClient({
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
networkInterface: createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
opts: {
// Additional fetch() options like `credentials` or `headers`
credentials: 'same-origin',
},
}),
});
}
and on the other side in my lib def I have:
declare module 'react-apollo' {
declare module.exports: any;
}
what should I type here(examples would be helpful) to have type checking?
Start from this detailed article.
For others trying to get Flow working with React Apollo:
Flow is no longer supported with React Apollo.
See this comment on GitHub.

Resources