Search code examples
javascriptreactjsgraphqlapolloapollostack

Having trouble using graphql's fragments with Apollo


My problem is quite simple, I need to get different menu functions depending on which type of user is logged in on my app (using react/redux/graphql/apollo).

I have it all working fine, but my graphql query to get the info I need currently looks like this:

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
                }
            }
        }
    }
}
`;

It's fairly obvious that I want to use fragments here, to make it look more like this:

my fragment would be something like

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

and the result I want:

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

I can't find a simple explanation on the doc, at least I don't get it right. I don't know if I need to create fragments server or client side, and how to properly do it. Can someone comfortable with graphql/apollo help me out on what to do here? Much appreciated!


Solution

  • So when you write your query, what you want to do is the following.

    1. Fragment on a type
    2. Specify the behavior on the fragment

    To generalize it

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

    This allows you to request specific fields depending on what type of user you are returning. You probably want to group your users under an "interface type" or a union so you can delineate the relationship.

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

    is a good guide going into more detail.