Graphql 将ImageSharp作为字段添加到MarkdownRemark节点(非frontmatter)

Graphql 将ImageSharp作为字段添加到MarkdownRemark节点(非frontmatter),graphql,gatsby,Graphql,Gatsby,我正在尝试使用以下graphQL查询: { allMarkdownRemark( limit: 1000 ) { edges { node { id parent { id } fields{ slug hero {

我正在尝试使用以下graphQL查询:

 {
      allMarkdownRemark(
        limit: 1000
      ) {
        edges {
          node {
            id
            parent {
              id
            }
            fields{
              slug
              hero {
                childImageSharp {
                  fixed {
                    src
                  }
                }
              }
            }
            frontmatter {
              template
            }
          }
        }
      }
    }
hero
字段当前使用以下代码返回图像的路径:

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  // Add slug to MarkdownRemark node
  if (node.internal.type === 'MarkdownRemark') {
    const value = createFilePath({ node, getNode, basePath: 'library' })
    const { dir } = getNode(node.parent)
    const getHero = (d) => {
      let hero = `${__dirname}/src/images/no-hero.gif`
      if (fs.existsSync(`${d}/hero.jpg`)) hero = `${d}/hero.jpg`
      if (fs.existsSync(`${d}/hero.png`)) hero = `${d}/hero.png`
      if (fs.existsSync(`${d}/hero.gif`)) hero = `${d}/hero.gif`
      return hero
    }
    createNodeField({
      node,
      name: 'slug',
      value,
    })

    createNodeField({
      node,
      name: 'hero',
      value: getHero(dir),
    })
  }
}
我见过其他人在
frontmatter
中对图像路径做过类似的操作,但我不想在让graphql看到文件路径而不必指定它的情况下使用frontmatter

但是,当我尝试上述操作时,我得到以下错误:

字段“英雄”不能有选择,因为类型“字符串”没有选择 子域

有没有办法让childImageSharp识别这个字段?

我再次(希望)一劳永逸地解决这个问题(见我们的历史记录)

这次,我们将把英雄图像的
ImageSharp
附加到
MarkdownRemark
节点。您的方法是正确的,但有一点需要注意:盖茨比似乎只识别相对路径,即以点开始的路径

您可以在代码中轻松解决此问题:

    const getHero = (d) => {
      let hero = `${__dirname}/src/images/no-hero.gif`

  -   if (fs.existsSync(`${d}/hero.jpg`)) hero = `${d}/hero.jpg`
  -   if (fs.existsSync(`${d}/hero.png`)) hero = `${d}/hero.png`
  -   if (fs.existsSync(`${d}/hero.gif`)) hero = `${d}/hero.gif`

  +   if (fs.existsSync(`${d}/hero.jpg`)) hero = `./hero.jpg`
  +   if (fs.existsSync(`${d}/hero.png`)) hero = `./hero.png`
  +   if (fs.existsSync(`${d}/hero.gif`)) hero = `./hero.gif`

      return hero
    }
    createNodeField({
      node,
      name: 'hero',
      value: getHero(dir),
    })
虽然我想提供一个可选的英雄搜索功能,但这应该是可行的。我们可以使用
fs.readdir
获取
dir
中的文件列表,然后找到名为“hero”的文件:

exports.onCreateNode = async ({
  node, actions,
}) => {
  const { createNodeField } = actions

  if (node.internal.type === 'MarkdownRemark') {
    const { dir } = path.parse(node.fileAbsolutePath)

    const heroImage = await new Promise((res, rej) => {

      // get a list of files in `dir`
      fs.readdir(dir, (err, files) => {
        if (err) rej(err)

        // if there's a file named `hero`, return it
        res(files.find(file => file.includes('hero')))
      })
    })

    // path.relative will return a (surprise!) a relative path from arg 1 to arg 2.
    // you can use this to set up your default hero
    const heroPath = heroImage 
      ? `./${heroImage}` 
      : path.relative(dir, 'src/images/default-hero.jpg')

    // create a node with relative path
    createNodeField({
      node,
      name: 'hero',
      value: `./${heroImage}`,
    })
  }
}
这样我们就不在乎英雄形象的外延是什么,只要它存在。我使用
String.prototype.includes
,但为了安全起见,您可能希望使用正则表达式传递允许的扩展列表,如
/hero.(png | jpg | gif | svg)/
。(我认为您的解决方案更具可读性,但我更喜欢每个节点只访问一次文件系统。)

您还可以使用查找默认英雄图像的相对路径

现在,这个graphql查询可以工作了:


(小)问题 然而,这种方法有一个小问题:它破坏了graphql过滤器类型!当我尝试基于
hero
进行查询和筛选时,出现以下错误:

也许盖茨比忘了重新推断英雄的类型,所以它不是一个
文件,而是一个
字符串。如果你需要过滤器工作,这很烦人

这里有一个解决办法:我们自己来做,而不是让盖茨比链接文件

exports.onCreateNode = async ({
  node, actions, getNode, getNodesByType,
}) => {
  const { createNodeField } = actions

  // Add slug to MarkdownRemark node
  if (node.internal.type === 'MarkdownRemark') {
    const { dir } = path.parse(node.fileAbsolutePath)
    const heroImage = await new Promise((res, rej) => {
      fs.readdir(dir, (err, files) => {
        if (err) rej(err)
        res(files.find(file => file.includes('hero')))
      })
    })

    // substitute with a default image if there's no hero image
    const heroPath = heroImage ? path.join(dir, heroImage) : path.resolve(__dirname, 'src/images/default-hero.jpg')

    // get all file nodes
    const fileNodes = getNodesByType('File')

    // find the hero image's node
    const heroNode = fileNodes.find(fileNode => fileNode.absolutePath === heroPath)
    createNodeField({
      node,
      name: 'hero___NODE',
      value: heroNode.id,
    })
  }
}
现在我们可以再次过滤
英雄
字段:

若你们不需要按英雄形象过滤内容,让盖茨比处理节点类型更可取


如果您在尝试时遇到问题,请告诉我。

我不敢相信我们终于解决了!我选择了中间的解决方案,因为它更干净,不需要过滤:)