【发布时间】:2020-06-03 20:12:09
【问题描述】:
我通常有一个包含对象数组的frontmatter,每个对象内部都有一个图像,该图像将引用相对于markdown文件的文件字符串。
问题是,数组有时可能是空的,这意味着 graphql 必须通过将所有值设置为非 null 来计算架构是什么,我已经能够使用简单的类型来做到这一点,例如使用 Gatsby 的字符串createSchemaCustomization,但我希望能够声明一个引用图像的字符串以使用 Image Sharp(因此 gatsby-transformer-sharp 可以在组件接收之前压缩图像)。
在 Gatsby 文档或图像清晰插件的任何地方似乎都没有为此提供模式类型。
我尝试使用File! 作为一种在数组为空时有效的类型,但是当您实际尝试引用真实图像时,它只会返回{ image: childImageSharp: null },这意味着 gatsby-transformer-sharp 不会像在File! 没有声明。
以下是我的架构的声明方式:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
features: [Feature!]!
}
type Feature {
title: String!
description: String!
image: File!
}
`;
createTypes(typeDefs);
};
这是我的 graphql 查询:
export const query = graphql`
query HomeQuery($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
features {
title
description
image {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
`;
还有我的降价文件,它返回特征对象数组,image 是应该创建流体图像清晰对象的字符串。
---
path: '/'
features:
- title: Barns
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
image: features-001.png
- title: Private Events
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
image: features-002.png
- title: Food and Drinks
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
image: features-003.png
- title: Spa
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
image: features-004.png
---
作为概述,一旦我删除了createSchemaCustomization 上的File!,所有图像都会显示出来,但是一旦数组为空,构建就会中断。
【问题讨论】:
标签: javascript graphql gatsby sharp gatsby-image