无法在Apollo中使用graphql的片段

时间:2017-05-23 12:44:51

标签: javascript reactjs graphql apollo apollostack

我的问题很简单,我需要获取不同的菜单功能,具体取决于我的应用程序登录的用户类型(使用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帮我解决这里的问题吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

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

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

    概括它

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

    这允许您根据要返回的用户类型请求特定字段。您可能希望将用户分组为"接口类型"或者工会,这样你就可以描绘这种关系。

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

    是一个很好的指南,详细介绍。