[英]Allow optional GraphQL data in Gatsby
我正在嘗試在我的gatsby-node.js
文件中構建一個支持可選值的類型。 我認為這是用[String!]!
.
如何在gatsby-node.js
上home.js
我在gatsby-node.js
創建的新類型?
gatsby-node.js:
const path = require('path');
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type markdownRemark implements Node {
frontmatter: Features
}
type Features {
title: [String!]!
description: [String!]!
}
`;
createTypes(typeDefs);
};
頁面/主頁/home.js:
export const query = graphql`
query HomeQuery($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
features {
title
description
}
}
}
}
`;
主頁.md:
---
path: "/"
features:
- title: Barns
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
- title: Private Events
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
- title: Food and Drinks
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
- title: Spa
description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
---
這需要起作用,以便如果home.md
的前端內容中的features
數組為空,則 GraphQL 不會拋出錯誤。
請不要告訴我總是在數組中至少包含一個值,因為這不切實際,我的解決方案需要在我的數組中不支持任何值。
我花了兩個小時在圈子里瀏覽文檔/問題試圖找到一個可行的解決方案,請有人救我!
來自GraphQL 文檔:
String!
表示該字段不可為空,這意味着 GraphQL 服務承諾在您查詢該字段時始終為您提供一個值。 在類型語言中,我們將用感嘆號表示那些。[Episode!]!
表示一個Episode
對象數組。 由於它也是不可為空的,因此當您查詢該字段時,您總是可以期待一個數組(具有零個或多個項目)。 從Episode!
也是不可為空的,您總是可以期望數組的每個項目都是一個Episode
對象。
感嘆號!
在 GraphQL 中意味着不可為空,所以[String!]!
意味着有一個非空字符串的非空數組。
如果您希望某個字段是可選的,請保持原樣,不帶感嘆號!
. 例如, [String]
表示該數組可以為空,或者其中的任何字符串值都可以為空。
我也不確定您是否想首先使用數組,因為功能的title
和description
肯定應該只是一個字符串?
根據Gatsby docs ,我認為您要尋找的是:
const typeDefs = `
type markdownRemark implements Node {
// Use custom frontmatter type
frontmatter: Frontmatter
}
// Define custom frontmatter type
type FrontMatter {
// Nullable array of Feature elements
features: [Feature]
}
// Feature has nullable fields title and description
type Feature {
title: String
description: String
}
`;
這意味着 frontmatter 有一個稱為features
的字段,該字段可以為 null(可選),並且如果它確實存在,則是一個Feature
對象數組。 它可以為空,但如果存在任何Feature
對象,則每個Feature
都有一個可為空(可選)的title
和description
字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.