【问题标题】:How to remove GraphQL fields according to other fields, in Gatsby?如何在 Gatsby 中根据其他字段删除 GraphQL 字段?
【发布时间】:2021-10-13 06:42:23
【问题描述】:

我有一个返回视频播放列表的页面查询。有些视频将“公开”设置为 true,有些则设置为 false。对于公共字段设置为 false 的视频,我不想在 Gatsby 发送到页面的有效负载中包含该视频的 URL,因为访问这些视频是付费的。

例子:

export const query = graphql`
    query MyQuery {
        courses: allSanityCourses {
            nodes {
                price
                name
                playlist {
                    title
                    url
                    public
                }
            }
        }
    }
`

以及它返回的数据:

[
    {
        "price": 149,
        "name": "Master VS Code",
        "playlist": [
            {
                "title": "Intro",
                "url": "https://youtu.be/qwertyuiop",
                "public": true
            },
            {
                "title": "Principles Part 1",
                "url": "https://youtu.be/poiuytrewq",
                "public": false
            }
        ]
    }
]

如何防止 Gatsby 将第二个 URL(将 public 设置为 false)发送到页面?

我不确定Query Filters 是否有效,因为它们似乎只允许根据相同字段的内容过滤/删除字段。我需要的是根据 another 同级字段“public”过滤/删除 URL 字段。

【问题讨论】:

    标签: graphql gatsby sanity


    【解决方案1】:

    我想你正在寻找:

    export const query = graphql`
        query MyQuery {
            courses: allSanityCourses(
            filter: {
              playlist: {
                public: { eq: true }
              }
            },
            ){
                nodes {
                    price
                    name
                    playlist {
                        title
                        url
                        public
                    }
                }
            }
        }
    `
    

    filter 过滤器(相当多余)和eq(等于)选项应该可以为您解决问题。如果需要,请在 localhost:8000/___graphql 操场上检查它。

    您可以在https://www.gatsbyjs.com/docs/query-filters/中查看更多过滤器

    【讨论】:

    • 我用查询 MyQuery { course: allSanityCourses( filter: { playlist: { elemMatch: { public: { eq: true} } } }, ){ nodes { price title playlist { title url public } } } } 并且它仍然返回所有播放列表元素,包括 public: false 。
    • 我解决了它here,但如果我能用 GraphQL 本身做到这一点,那就更好了。
    • 你试过我的吗? (eq 代替 elemMatch)
    • 是的,对不起,我忘了告诉你它导致了一个错误:字段“public”不是由类型“SanityVideoFilterListInput”定义的。
    • 那你没有过滤allSanityCourses节点
    猜你喜欢
    • 2021-03-29
    • 2012-05-11
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2018-04-23
    • 2023-04-06
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多