How to send GraphQL mutation from one server to another?

丶灬走出姿态 提交于 2020-01-31 08:35:27

问题


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.



来源:https://stackoverflow.com/questions/45920986/how-to-send-graphql-mutation-from-one-server-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!