简体   繁体   English

如何将数据的JSON格式转换为GraphQL查询格式

[英]How to convert JSON format of data to GraphQL query format

I have a Json object and want to convert it to graphql query in order to post a request on graphql api.我有一个 Json 对象,想将它转换为 graphql 查询,以便在 graphql api 上发布请求。 Can any one please provide any pointer to it as I am not able to proceed.任何人都可以提供任何指向它的指针,因为我无法继续。

JSON object extracted from the POJO:
{
  "customer": {
     "idFromSource": "123", 
     "title": "Mrs", 
     "dateOfBirth": "1980-11-11"
  }
}

graphql query that I need to hit a post request:
{
  "query": "mutation {updateCustomer(customer: 
                    {idFromSource: \"123\", 
                    title: \"Mrs\", 
                    dateOfBirth: \"1980-11-11\"})
                     {idFromSource title dateOfBirth}}"
}

Declare the input as a variable in your query.在查询中将输入声明为变量。 Queries should be static . 查询应该是静态的 That means you never generate GraphQL code on the client.这意味着您永远不会在客户端生成 GraphQL 代码。 If you are doing that you are probably doing something wrong.如果你这样做,你可能做错了什么。 I am not sure which frontend technology you are using but here is your query using JavaScript fetch:我不确定您使用的是哪种前端技术,但这是您使用 JavaScript fetch 的查询:

let json = // ... parsed JSON

let query = `
  mutation customerMutation($customer: CustomerInput) { # Adjust typename
    updateCustomer(customer: $customer) {
      idFromSource
      title
      dateOfBirth
    }
  }
`;

fetch('/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  data: JSON.stringify({
    query,
    variables: { customer: json.customer }
  }),
});

The trick is that there is a type on the GraphQL API (I have here assumed it is called CustomerInput , please adjust it in the mutation) that has the same shape as your JSON object.诀窍是 GraphQL API 上有一个类型(我在这里假设它被称为CustomerInput ,请在突变中调整它)与您的 JSON 对象具有相同的形状。 The server will therefore happily accept the whole JSON object as a value for the $customer variable in the mutation.因此,服务器很乐意接受整个 JSON 对象作为变异中$customer变量的值。 No conversion needed!无需转换!

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

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