Tương tác với API GraphQL
Tương tác với API GraphQLThay đổi đường dẫn nơi một trường được in trong phản hồi

Thay đổi đường dẫn nơi một trường được in trong phản hồi

Câu hỏi này đã xuất hiện trên Reddit:

I have:

allMdx {
  edges {
    node {
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
      }
    }
  }
}

I need frontmatter.date to be publishedAt:

allMdx {
  edges {
    node {
      publishedAt: frontmatter{date(formatString: "MMMM DD, YYYY")}
    }
  }
}

Problem is, when I do this, I end up with:

{
  "publishedAt": {
    "date": "February 06, 2021"
  }
}

Instead of (which is what I need):

{
  "publishedAt": "February 06, 2021"
}

Is it even possible to alias nested fields like this?

Nói cách khác, liệu có thể yêu cầu máy chủ GraphQL làm phẳng cấu trúc phản hồi không? Nếu có, thì làm thế nào?

Dưới đây là một giải pháp với Gato GraphQL, sử dụng các tiện ích mở rộng sau:

Với @export, chúng ta có thể để một thao tác query đầu tiên xuất một kết quả vào biến, sau đó khai báo một thao tác query thứ hai sẽ đọc biến này và in nó ở vị trí mong đợi trong phản hồi:

query ExportDate
{
  allMdx {
    edges {
      node {
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
            @export(as: "date")
        }
      }
    }
  }
}
 
query PrintRelocatedDate($date: String)
  @depends(on: "ExportDate")
{
  allMdx {
    edges {
      node {
        publishedAt: _echo(value: $date)
      }
    }
  }
}

...và sau đó thực thi query (truyền ?operationName=PrintRelocatedDate) sẽ tạo ra phản hồi này:

{
  "data": {
    "allMdx": {
      "edges": [
        {
          "frontmatter": {
            "publishedAt": "February 06, 2021"
          },
          "publishedAt": "February 06, 2021"
        }
      ]
    }
  }
}