Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apollo in node - (no react)

I want to use apollo to do some batch updates. And I need to start the batch script from node. eg node myscript.js

I can't figure out how to do this.  Is there a simple example that does what is described on the Get started: https://www.apollographql.com/docs/react/get-started/ but without react ?

(My code is working just fine when using react)

like image 566
terchris Avatar asked Jul 13 '26 14:07

terchris


2 Answers

This is how to use Apollo Client ver 3.x from node vs using it from React

To use it from node you must import from @apollo/client/core in React you import from @apollo/client So initializing in node can look like this:

const STRAPIURI = "http://192.168.39.174:1337/graphql";
import fetch from 'cross-fetch';
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client/core';

const apolloClient = new ApolloClient({
  link: new HttpLink({
    uri: `${STRAPIURI}`, fetch,
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
  }),
  cache: new InMemoryCache()
});

You also need to import gql from the same location.

import { gql } from '@apollo/client/core';
like image 96
terchris Avatar answered Jul 21 '26 09:07

terchris


First you need create an apollo client, very similar to react.

Check the below code.


import { ApolloClient } from 'apollo-client';
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import config from './config';

const httpLink = createHttpLink({
  uri: `${config.apiUrl}/graphql`,
  fetch,
});

const authLink = setContext(() => {
  const token = config.serverToken;
  return {
    headers: {
      Authorization: token,
    },
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});


export default client;

Once is the client is done, you can use the below code to do a mutation

import gql from 'graphql-tag';

const mutation = gql(`mutation {
    CreateTodo(
      data: {
        task: "${task}"
      }
    ) {
      id
      task
    }
  }`);

const response = await client.mutate({mutation});

You can similarly use it for query as well. We are using node fetch to make the query or mutation.

Let me know if it helps.

like image 33
Sakti Chourasia Avatar answered Jul 21 '26 09:07

Sakti Chourasia