【问题标题】:Manually define schema using gatsby-transformer-json使用 gatsby-transformer-json 手动定义模式
【发布时间】:2018-07-28 11:26:17
【问题描述】:

我有两个现有的 JSON 文件,一个包含位置信息,另一个包含帖子信息,其中包含位置和帖子 ID:

locations.json:

[
  {
    "locationId": "location-id-1",
    "name": "name-2",
    "posts": ["post-id-1", "post-id-2"]
  },
  {
    "locationId": "location-id-2",
    "name": "name-2",
    "posts": ["post-id-3", "post-id-4", "post-id-5"]
  },
  // ...
]

posts.js:

[
  {
    "postId": "post-id-1",
    "title": "some-title-1",
    "locationId": "location-id-1",
    "text": "..."
  },
  {
    "postId": "post-id-2",
    "title": "some-title-2",
    "locationId": "location-id-1",
    "text": "..."
  },
  // ...
]

我正在使用gatsby-transformer-json,它允许我使用allLocationsJsonallPostsJson 创建GraphQL 查询。但是,我不知道如何更改 GraphQL 架构以允许这样的查询:

{
  allLocationsJson {
    edges {
      node {
        locationId
        name
        posts {
          postId
          title
          text
        }
      }
    }
  }
}

问题在于posts 字段,因为GraphQL 没有意识到我希望posts 成为帖子对象的列表,而不仅仅是帖子ID。我有什么办法可以用我现有的 JSON 结构完成这种查询吗?

【问题讨论】:

    标签: graphql gatsby


    【解决方案1】:

    Gatsby 处理以___NODE 结尾的特殊字段。当 Gatsby 为这些字段创建模式时,它会将它们转换为指向其他类型的链接。因此,如果您将locations.json 上的posts 字段重命名为posts___NODE,那么您将能够根据需要查询数据。

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 1970-01-01
      • 2019-05-27
      • 2019-03-17
      • 2020-03-20
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多