代码之家  ›  专栏  ›  技术社区  ›  Sam

Graphql:如果参数的类型是字符串,则跳过该参数

  •  0
  • Sam  · 技术社区  · 5 年前

    我有一个针对Markdown文件的graphql查询,它请求 title , author coverImg 从Markdown的首页开始。

    有些Markdown文件没有封面图像,当没有图像时,看起来coverImg的类型是String

    我正在使用 gatsby-image 它使用 sharp 我想深入探讨一下 封面Img 参数,如果 封面Img 是一个对象,而不是字符串


    这是我的问题

    query($path: String!) {
        markdownRemark(fields: { slug: { eq: $path } }) {
            frontmatter {
                title
                author
                coverImg {
                  childImageSharp {
                    fluid(maxWidth: 600) {
                      src
                      srcSet
                      sizes
                      aspectRatio
                    }
                  }
               }
            }
         }
     }
    

    如果我尝试这样做,我会收到错误

    There was an error in your GraphQL query:
    
    Field "cover" must not have a selection since type "String" has no subfields.
    
    This can happen if you e.g. accidentally added { } to the field "cover". If you didn't expect "cover" to be of type "String" make sure that your input source and/or plugin is correct.
    

    看起来有 graphql if statements 但我不知道如何使用这些来有条件地分支给孩子。如果我能添加以下内容,那就太好了

     coverImg @skip(if: coverImg is String) {
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   Derek Nguyen    5 年前

    AFAIK-Gatsby不会在每个文件的基础上推断数据的模式,因此一旦它推断出一个字段为 String ,该字段将始终为类型 字符串 .

    您可以使用模式自定义挂钩告诉Gatsby该字段 coverImg 是一个文件(正如@ksav在评论中所建议的那样):

    exports.createSchemaCustomization = ({ actions }) => {
      actions.createTypes(`
        type MarkdownRemarkFrontmatter @infer {
          coverImg: File
        }
    
        type MarkdownRemark implements Node @infer {
          frontmatter: MarkdownRemarkFrontmatter
        }
      `)
    }
    

    然后你可以检查一下 封面Img 存在。

    if (!coverImg) {
      // no image
    } else if (coverImg.childImageSharp) {
      // has image
    } else {
      // file is not an image
    }
    
        2
  •  0
  •   JuanCaicedo    5 年前

    一、 认为 应该可以用它做你想做的事 graphql union types 。我从来没有在对象和字符串上使用过它们,但应该有办法做到这一点