简体   繁体   中英

How to create/generate GraphQL query programatically in Java

I'm new in GraphQL with Java, so I understand that having this model:

type Comment {
    id: ID!
    name: String!
    message: String!
}

I need to generate (and send to an API) this query to insert a entry:

mutation {
  createComment(data: { name: "Face Mask", message: "face-mask" }) {
    id
    name
  }
}

I was looking a programatically way to generate this string in Java with some library, but i can't find anything.

We are wondering if there is a more generic way rater than write a "hard coded" string and then replace the values.

We are running a spring boot server, as a REST API and we need to save the comments in GraphCMS (now Hygraph) besides to a MySql database (already working).

Instead of writing an "hard coded" string and then replace the values, you could use GraphQL variables in your mutation.

Variables need to be declared in your mutation (or query or subscribtion), and can then be used everywhere inside your operation. The values for the variables are sent as an extra (JSON) object to your GraphQL endpoint (somehow comparable to a prepared SQL statement).

mutation CreateComment($name: String!, $message: String!) {
  createComment(data: { name: $name, message: $message }) {
    id
    name
  }
}

How the variables are sent to your GraphQL API depends on your client library. In general you would create the "normal" HTTP POST request with your GraphQL query but in addition a variables field that contains the variable names and values as an object:

{
  "query": "mutation CreateComment($name: String!, $message: String!) .....",
  "variables": {"name":"Face Mask", "message": "face-mask"}
}

More on variables in the GraphQL docs: https://graphql.org/learn/queries/#variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM