微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Gatsby 上为外部图像正确创建类型定义

如何解决如何在 Gatsby 上为外部图像正确创建类型定义

我使用 Gatsby 3.6.1,带有 Gatsby plugin image。我正在从返回以下结构的 API 中获取图像:

[
   {
     "pk": 1,"url": "https://location_of_the_image1",},{
     "pk": 2,"url": "https://location_of_the_image2",]

这些图像存储在节点 API__Image 中,然后我使用 createRemoteFileNodeAPI__Image.image 字段中创建文件的本地版本:

exports.onCreateNode = async ({
  node,actions: { createNode },store,cache,createNodeId,}) => {
  if (node.internal.type === `API__Image` && node.pk) {
    let fileNode = await createRemoteFileNode({
      url: node.url,// string that points to the URL of the image
      parentNodeId: node.id,// id of the parent node of the fileNode you are going to create
      createNode,// helper function in gatsby-node to generate the node
      createNodeId: id => `IMG${node.pk}`,// Gatsby's cache
      store,// Gatsby's Redux store
    })
    // if the file was created,attach the new node to the parent node
    if (fileNode) {
      node.image___NODE = fileNode.id
    }
  }
}

此设置的问题在于,在多次使用 gatsby developgatsby build 时会返回以下错误

Invariant Violation: Encountered an error trying to infer a GraphQL type for: "image___NODE". There is no corresponding node with the "id" field matching: "IMG286,IMG287...

我应该如何为这段代码创建正确的类型定义?我已经尝试按照 this page 的示例进行操作,但我一直收到相同的错误

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = `
  type API__Image implements Node {
    pk: ID!
    url: String!
    image: File @link(from: "image___NODE")

  }
`
  createTypes(typeDefs)
}

一个有趣的问题,为什么节点内部类型被称为 API__Image,但在 http://localhost:8000/___graphql 处访问 GraphQL 时,它显示apiImage?定义 GraphQL 类型时应该使用 API__Image 还是 apiImage

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。