【问题标题】:Having trouble using graphql's fragments with Apollo在 Apollo 中使用 graphql 的片段时遇到问题
【发布时间】:2017-10-23 10:21:41
【问题描述】:

我的问题很简单,我需要根据登录我应用的用户类型(使用 react/redux/graphql/apollo)来获得不同的菜单功能。

我的一切工作正常,但我的 graphql 查询以获取我当前需要的信息如下所示:

const currentUsr = gql`
query getCurrentUser {
    getCurrentUser{
        firstname,
        id_users,
        menuItem {
            title,
            url,
            id_parent,
            is_parent,
            icon,
            id_menu_item,
            childs {
                title,
                url,
                id_parent,
                is_parent,
                icon,
                id_menu_item,            
                childs {
                    title,
                    url,
                    id_parent,
                    is_parent,
                    icon,
                    id_menu_item
                }
            }
        }
    }
}
`;

很明显我想在这里使用片段,让它看起来更像这样:

我的fragment 会是这样的

fragment itemInfo{
    title,
    title,
    url,
    id_parent,
    is_parent,
    icon,
    id_menu_item
}

和我想要的结果:

const currentUsr = gql`
query getCurrentUser {
    getCurrentUser{
        firstname,
        id_users,
        menuItem {
            ...itemInfo
            childs {
                ...itemInfo
                childs {
                    ...itemInfo
                }
            }
        }
    }
}

我在文档上找不到简单的解释,至少我没有理解正确。我不知道我是否需要创建片段服务器或客户端,以及如何正确地做到这一点。对graphql / apollo感到满意的人可以帮助我在这里做什么吗?非常感谢!

【问题讨论】:

    标签: javascript reactjs graphql apollo apollostack


    【解决方案1】:

    因此,当您编写查询时,您想要做的就是以下内容。

    1. 类型上的片段
    2. 指定片段的行为

    概括一下

    query {
     _id
     name
     ... on UserType1 {
       #UserType1Fieldshere
     }
     ... on UserType2 {
       #UserType2fieldshere
     }
    

    这允许您根据返回的用户类型请求特定字段。您可能希望将用户分组到“接口类型”或联合下,以便描述关系。

    这里:https://medium.com/the-graphqlhub/graphql-tour-interfaces-and-unions-7dd5be35de0d

    是一个很好的指南,可以更详细地介绍。

    【讨论】:

    • 总体上帮助我了解 Fragments 和 graphql,谢谢 :)
    猜你喜欢
    • 2023-03-19
    • 2015-06-16
    • 1970-01-01
    • 2017-02-20
    • 2020-01-17
    • 1970-01-01
    • 2019-12-28
    • 2013-06-23
    • 2018-04-12
    相关资源
    最近更新 更多