VikR
VikR

Reputation: 5142

Apollo GraphQL: Call a Mutation from the Server?

I need to call a mutation from a cron job running on the server. I found this SO post, but the accepted answer said there was no way to do it.

Then I found this on GitHub, from 2017:

graphql-server is a network wrapper for graphql core function. if you don't want to use it over network, you can just run it standalone:

import scheme from './scheme';

const query = `{
  me {
    name   
  }
}`;

const result = graphql(scheme, query);
console.log(result); 

function documentation can be found here

That looks pretty good! Is that the best practices approach in 2020?

Upvotes: 2

Views: 1532

Answers (2)

VikR
VikR

Reputation: 5142

I just found out about this approach as well. It's possible to create an Apollo client directly on the server.

export const getApolloServerClient = () =>

  new ApolloClient({

    ssrMode: true,

    cache: new InMemoryCache(),

    link: new SchemaLink({ schema }),

  });

Upvotes: 0

Daniel Rearden
Daniel Rearden

Reputation: 84687

Yes, if you have access to the GraphQLSchema object used by your GraphQL server, then the simplest approach is to just use the graphql function exported by the graphql module. Note that you should await the returned Promise to access the result:

async function run () {
  const { data, errors } = await graphql(
    schema, 
    query,
    rootValue,
    context,
    variables
  )
}

However, you can also make requests to the server itself over the network -- if the server is on the same host, you'd just use localhost or 127.0.0.1. In that case, you can use axios, request or any other HTTP client library in a Node.js script. You can also just use curl to make the request directly in a bash script or curl command.

Upvotes: 1

Related Questions