【问题标题】:How to convert JSON format of data to GraphQL query format如何将数据的 JSON 格式转换为 GraphQL 查询格式
【发布时间】:2020-05-11 12:20:55
【问题描述】:

我有一个 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}}"
}

【问题讨论】:

标签: java json graphql


【解决方案1】:

在查询中将输入声明为变量。 Queries should be static。这意味着您永远不会在客户端上生成 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 变量的值。无需转换!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2021-12-05
    • 2020-08-30
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多