Search code examples
graphqlapollo

How to use arguments with include directive in Apollo GraphQL?


So for starters, this is my code:

export const GET_AUTHORIZED_USER = gql`
    query GetAuthorizedUser(
        $includeReviews: Boolean!
        $after: String
        $first: Int
    ) {
        authorizedUser {
            id
            username
            reviews @include(if: $includeReviews) {
                pageInfo {
                    hasPreviousPage
                    hasNextPage
                    startCursor
                    endCursor
                }
                edges {
                    cursor
                    node {
                        id
                        repositoryId
                        rating
                        text
                        createdAt
                        user {
                            username
                        }
                    }
                }
            }
        }
    }
`;

reviews accepts $after and $first arguments, but my problem is that I cannot figure out how to add them. If I remove @includes directive, and add the arguments, it works fine. In my case, I want to have both the directive and the arguments.

How can I achieve this? I know that I can make a separate query for fetching the reviews, but I want to use the directive.


Solution

  • So, apparently adding the arguments before the @include directive is the way. I tried many different ways and this worked like a charm! So if anyone is wondering how to also add arguments besides directives, this is how:

    export const GET_AUTHORIZED_USER = gql`
        query GetAuthorizedUser(
            $includeReviews: Boolean!
            $after: String
            $first: Int
        ) {
            authorizedUser {
                id
                username
                reviews(after: $after, first: $first) @include(if: $includeReviews) {
                    pageInfo {
                        hasPreviousPage
                        hasNextPage
                        startCursor
                        endCursor
                    }
                    edges {
                        cursor
                        node {
                            id
                            repositoryId
                            rating
                            text
                            createdAt
                            user {
                                username
                            }
                        }
                    }
                }
            }
        }
    `;