I need a graphql client lib to run on node.js for some testing and some data mashup - not in a production capacity. I'm using apollo everywhere else (react-apollo
, apollo's graphql-server-express
). My needs are pretty simple.
Is apollo-client
a viable choice? I can find no examples or docs on using it on node - if you're aware of any, please share.
Or maybe I should/can use the reference graphql client on node?
Apollo Client should work just fine on Node. You only have to install cross-fetch because it assumes fetch
exists.
Here is a complete TypeScript implementation of Apollo Client working on Node.js.
import ApolloClient, { gql } from "apollo-boost"; import { InsertJob } from "./graphql-types"; import 'cross-fetch/polyfill'; const client = new ApolloClient({ uri: "http://localhost:3000/graphql" }); client.mutate<InsertJob.AddCompany, InsertJob.Variables>({ mutation: gql`mutation insertJob($companyName: String!) { addCompany(input: { displayName: $companyName } ) { id } }`, variables: { companyName: "aaa" } }) .then(result => console.log(result));
Newer Apollo version provide a simpler approach to perform this, as described in Apollo docs, check the section "Standalone". Basically one can simply use ApolloLink
in order to perform a query or mutation.
Below is copy of the example code from the docs as of writing this, with node-fetch
usage as config to createHttpLink
. Check the docs for more details on how to use these tools.
import { execute, makePromise } from 'apollo-link'; import { createHttpLink } from 'apollo-link-http'; import gql from 'graphql-tag'; import fetch from 'node-fetch'; const uri = 'http://localhost:4000/graphql'; const link = createHttpLink({ uri, fetch }); const operation = { query: gql`query { hello }`, variables: {} //optional operationName: {} //optional context: {} //optional extensions: {} //optional }; // execute returns an Observable so it can be subscribed to execute(link, operation).subscribe({ next: data => console.log(`received data: ${JSON.stringify(data, null, 2)}`), error: error => console.log(`received error ${error}`), complete: () => console.log(`complete`), }) // For single execution operations, a Promise can be used makePromise(execute(link, operation)) .then(data => console.log(`received data ${JSON.stringify(data, null, 2)}`)) .catch(error => console.log(`received error ${error}`))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With