Json to Graphql conversion

2020-02-16 05:15发布

问题:

I have a Json object and I want to convert it graphql mutation query inorder to invoke a graphql api. So my requirement is I need to create a springboot project and expose a POST API which will take input as a json and convert it into graphql mutation query format, then I need to consume a graphql api with the mutation query. Can any one please provide any pointer to it as I am not able to proceed.

回答1:

Pass your object as a variable. You are able to put it in JSON format in the Graphql variables definitions.

If you look at the official tutorial on mutations, in the query, they pass the ReviewInput as a variable, $review:

mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
  createReview(episode: $ep, review: $review) {
    stars
    commentary
  }
}

As the ReviewInput is, at in my use case, a standard object from the model, used for both REST and GraphQl, the JSON can be directly pasted in the GraphQl in the corresponding review field in the GraphQl variables:

{
  "ep": "JEDI",
  "review": {
    "stars": 5,
    "commentary": "This is a great movie!"
  }
}

{ "stars": 5, "commentary": "This is a great movie!" } being your JSON.

So, in short, no conversion is required, you just need your API to put the JSON in the correct mutation template.