我有一个 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}}"
}
最佳答案
将输入声明为查询中的变量。 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
变量的值。无需转换!
关于java - 如何将 JSON 格式的数据转换为 GraphQL 查询格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908872/