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

7

我有一个Json对象,想要将其转换为graphql查询以便在graphql api上发布请求。请问有人可以提供任何指针吗?我无法继续进行。

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}}"
}

请查看 https://stackoverflow.com/a/59577657/1776132。 - Smile
1
@Ash Raf,你可以使用类似于这个的东西 https://github.com/dupski/json-to-graphql-query#readme - Yogeshwar Tanwar
1个回答

5

在查询中将输入声明为变量。 查询应该是静态的。这意味着您永远不会在客户端生成GraphQL代码。如果您正在这样做,那么您可能正在做错事情。我不确定您正在使用哪种前端技术,但以下是使用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 }
  }),
});

诀窍在于,GraphQL API 中有一种类型(我在这里假定它被称为 CustomerInput,请根据您的情况进行调整),其形状与您的 JSON 对象相同。因此,服务器将愉快地接受整个 JSON 对象作为变异中 $customer 变量的值。无需转换!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接