小编Joe*_*ven的帖子

Gatsby graphql 查询带有空数组的 json 数据会抛出错误

我正在尝试查询一些可能包含空数组的 JSON 数据,JSON 文件将可以通过 CMS 访问,因此它必须支持为空,但是,当 gatsby 尝试查询空数组时,它会抛出错误(大概是因为我'我试图查询数组内对象内的项目)。

Gatsby 有没有办法查询 JSON 文件但期望数组为空?(使里面的对象可选?)。

这是我在代码中遇到的困境:

careers.json

{
    "title": "Careers",
    "subtitle": "Looking for an exciting new career change?",
    "jobs": [
        {
            "title": "Job 01",
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Curabitur blandit tempus porttitor."
        }
    ]
}

Run Code Online (Sandbox Code Playgroud)

jobs当没有任何作业时,上面的 JSON 属性也将是一个空数组,如下所示:

{
    "title": "Careers",
    "subtitle": "Looking for an exciting new career …
Run Code Online (Sandbox Code Playgroud)

javascript json graphql gatsby

5
推荐指数
0
解决办法
1004
查看次数

如何在graphql gatsby中允许可选的清晰图像?

我通常有frontmatter,它将包含一个对象数组,每个对象内部将是一个图像,该图像将引用与markdown文件相关的文件字符串。

问题是,数组有时可能是空的,这意味着 graphql 必须通过将所有值设置为非空来确定架构是什么,我已经能够使用 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);
};
Run Code Online (Sandbox Code Playgroud)

这是我的 graphql 查询:

export const query = …
Run Code Online (Sandbox Code Playgroud)

javascript graphql gatsby sharp gatsby-image

5
推荐指数
1
解决办法
856
查看次数

标签 统计

gatsby ×2

graphql ×2

javascript ×2

gatsby-image ×1

json ×1

sharp ×1