Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send GraphQL mutation from one server to another?

I would like to save some Slack messages to a GraphQL backend. I can use the Slack API and what they call "Slack App Commands" so everytime a message is send to my Slack channel, Slack will automatically send a HTTP POST request to my server with the new message as data.

I was thinking using an AWS lambda function to forward this post request to my GraphQL server endpoint (I am using GraphCool). I am pretty new to GraphQL, I've used Apollo to create mutations from the browser. Now I need to send mutation from my Node server (AWS Lambda function) instead of the browser. How can I achieve that?

Thanks.

like image 421
Damien Monni Avatar asked Aug 28 '17 14:08

Damien Monni


2 Answers

GraphQL mutations are simply HTTP POST requests to a GraphQL endpoint. You can easily send one using any HTTP library such as request or axios.

For example, this mutation,

mutation ($id: Int!) {
  upvotePost(postId: $id) {
    id
  }
}

and query variable,

$id = 1

is an HTTP POST request with a JSON payload of

{
  "query": "mutation ($id: Int!) { upvotePost(postId: $id) { id } } ", 
  "variables": { "id": 1 } 
}

Take note that query is your GraphQL query as a string.

Using axios as an example, you can send this to your server using something like this,

axios({
  method: 'post',
  url: '/graphql',
  // payload is the payload above
  data: payload,
});
like image 79
Noel Llevares Avatar answered Sep 21 '22 04:09

Noel Llevares


Setting up an AWS Lambda is left as an exercise for the reader.

To get to see what GraphQL queries (or in this case, mutations) your Apollo client code is sending to the server, for cutting+pasting (and presumably parameterising) into your lambda code, this tool exists: Apollo GraphQL Dev Tools which now allows you to watch your mutations being executed.

like image 33
Ed. Avatar answered Sep 21 '22 04:09

Ed.