簡體   English   中英

如何將數據的JSON格式轉換為GraphQL查詢格式

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

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

在查詢中將輸入聲明為變量。 查詢應該是靜態的 這意味着您永遠不會在客戶端生成 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變量的值。 無需轉換!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM