How to send GraphQL mutation from one server to another?
Asked Answered
T

2

17

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.

Tertia answered 28/8, 2017 at 14:7 Comment(0)
M
46

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,
});
Mauve answered 15/9, 2017 at 16:52 Comment(1)
Thank you! I finaly used graphql-request wich works fine but now I understand better how it works. :)Tertia
J
1

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.

Jargonize answered 15/9, 2017 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.