How to send GraphQL mutation from one server to an

2019-04-06 22:19发布

问题:

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.

回答1:

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,
});


回答2:

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.