简体   繁体   English

如何在 Java 中以编程方式创建/生成 GraphQL 查询

[英]How to create/generate GraphQL query programatically in Java

I'm new in GraphQL with Java, so I understand that having this model:我是 GraphQL 和 Java 的新手,所以我知道有这个 model:

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

I need to generate (and send to an API) this query to insert a entry:我需要生成(并发送到 API)这个查询来插入一个条目:

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.我正在寻找一种以编程方式在 Java 中使用一些库生成此字符串的方法,但我找不到任何东西。

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). 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.您可以在突变中使用 GraphQL 变量,而不是编写“硬编码”字符串然后替换值。

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).变量的值作为额外的 (JSON) object 发送到您的 GraphQL 端点(某种程度上与准备好的 SQL 语句相当)。

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.变量如何发送到您的 GraphQL API 取决于您的客户端库。 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:通常,您将使用 GraphQL 查询创建“正常”HTTP POST 请求,但另外还有一个包含变量名称和值的variables字段作为 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更多关于 GraphQL 文档中的变量: https://graphql.org/learn/queries/#variables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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