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

Ash*_*Raf 7 java json graphql

我有一个 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}}"
}
Run Code Online (Sandbox Code Playgroud)

Her*_*rku 6

将输入声明为查询中的变量。查询应该是静态的。这意味着您永远不会在客户端上生成 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 }
  }),
});
Run Code Online (Sandbox Code Playgroud)

诀窍在于 GraphQL API 上有一个类型(我在这里假设它被称为CustomerInput,请在突变中调整它)与 JSON 对象具有相同的形状。因此,服务器会愉快地接受整个 JSON 对象作为$customer突变中变量的值。无需转换!