Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does apollo-client work on node.js?

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?

like image 913
Ed Staub Avatar asked Nov 24 '16 17:11

Ed Staub


2 Answers

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)); 
like image 150
André Pena Avatar answered Sep 19 '22 14:09

André Pena


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}`)) 
like image 37
kaskelotti Avatar answered Sep 20 '22 14:09

kaskelotti