Graphql 如何结合gatsby片段创建gatsby模式
我试图为gatsby graphql查询定义正确的模式,以便它可以返回null(以使内容可选)。据我所知,我需要在gatsby-node.js文件中预定义模式,以便gatsby不必通过数据推断类型。但是,我不确定模式定义需要是什么,因为我们使用的是盖茨比片段来查询数据。这是查询的(部分):Graphql 如何结合gatsby片段创建gatsby模式,graphql,gatsby,Graphql,Gatsby,我试图为gatsby graphql查询定义正确的模式,以便它可以返回null(以使内容可选)。据我所知,我需要在gatsby-node.js文件中预定义模式,以便gatsby不必通过数据推断类型。但是,我不确定模式定义需要是什么,因为我们使用的是盖茨比片段来查询数据。这是查询的(部分): ... on ContentfulWorkPage { comingSoon { id title image { fluid(quality: 92, maxWidth: 1
... on ContentfulWorkPage {
comingSoon {
id
title
image {
fluid(quality: 92, maxWidth: 1280) {
...GatsbyContentfulFluid_withWebp_noBase64
}
}
comingSoonText
}
}
问题是,我不确定如何使用WebP\u noBase64定义GatsbyContentfulFluid\u
我正在尝试的是:
const types = `
type ContentfulWorkPage implements Node {
comingSoon: ComingSoon
}
type ComingSoon {
id: String
title: String
comingSoonText: String
image: Image
}
type Image {
fluid: Fluid
}
type Fluid {
quality: Int
maxWidth: Int
title: String
}
`
createTypes(types)
尽管我认为我走上了正确的道路,但我仍然会遇到以下错误:
There was an error in your GraphQL query:
Unknown argument "quality" on field "fluid" of type "Image".
GraphQL request:70:21
69 | image {
70 | fluid(quality: 92, maxWidth: 1280) {
| ^
71 | ...GatsbyContentfulFluid_withWebp_noBase64
File: src/templates/mainPages/work.js:105:21
ERROR #85901 GRAPHQL
There was an error in your GraphQL query:
Unknown argument "maxWidth" on field "fluid" of type "Image".
GraphQL request:70:34
69 | image {
70 | fluid(quality: 92, maxWidth: 1280) {
| ^
71 | ...GatsbyContentfulFluid_withWebp_noBase64
File: src/templates/mainPages/work.js:105:34
ERROR #85901 GRAPHQL
There was an error in your GraphQL query:
Fragment "GatsbyContentfulFluid_withWebp_noBase64" cannot be spread here as objects of type "Fluid" can never be of type "ContentfulFluid".
GraphQL request:71:17
70 | fluid(quality: 92, maxWidth: 1280) {
71 | ...GatsbyContentfulFluid_withWebp_noBase64
| ^
72 | }
因此,在翻阅了盖茨比的文档()之后,我设法解决了这个问题。我发现在gatsby node.js
文件中,可以使用printTypeDefinitions
函数打印数据类型,然后可以使用该函数预先定义可选属性:
exports.createSchemaCustomization= ({ actions }) => {
actions.printTypeDefinitions({path: './typeDefs.txt'})
}
这将在根文件夹中创建一个typeDefs.txt
文件,其中描述了所有推断的类型。因此,如果您正在寻找像我一样更复杂的type def,以便它们可以在contentful中成为可选的,那么您可以:
- 在contentful(或您正在使用的任何后端/服务器)中向可选字段添加一些数据
- 使用函数从数据中获取类型定义
- 从typeDefs文件中复制您需要的任何部分,然后
- 在
createSchemaCustomization
示例(comingSoon
定义是从typeDevs文件复制的):
额外提示:如果您只需要指定一个属性作为可选属性,但其余属性可以推断。删除@dontInfer
注释,只复制可为null的属性,而不是从文件中复制整个类型。非常感谢,printTypeDefinition真是一个救命稻草!
exports.createSchemaCustomization = ({ actions }) => {
const contentfulSomePage = `
type ContentfulSomePage implements Node {
comingSoon: [ContentfulCaseComingSoon] @link(by: "id", from: "comingSoon___NODE")
}
type ContentfulCaseComingSoon implements Node @derivedTypes @dontInfer {
title: String
comingSoonText: String
image: ContentfulAsset @link(by: "id", from: "image___NODE")
}
`
actions.createTypes(contentfulWorkPage)
}