使用 gatsby-transformer-json 手动定义模式

Manually define schema using gatsby-transformer-json

我有两个现有的 JSON 文件,一个包含位置信息,另一个 post 信息,其中包含位置和 post 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 成为 post 对象的列表,而不仅仅是 post ID。我有什么办法可以用我现有的 JSON 结构完成这种查询吗?

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