JavaScript/GraphQL add fragments conditionally

Viewed 984

I have a JavaScript function that sends a fetch request to a graphQL endpoint. My goal is to add a fragment to my graphQL query based a parameter passed into the JavaScript function, for example, my function looks like this:

const getEvent = async (id, lang) => {
    const data = await fetchAPI(`
        fragment EventFields on Event {
            title
            slug
            date
        }
        fragment BnFields on Event {
            bn {
                content
                subtitle
            }
        }
        query fetchEvent($id: ID!, $idType: EventIdType!) {
            event(id: $id, idType: $idType) {
                ...EventFields
                content
            }
        }
    }
}

I would like to add the BnFields fragment if the lang parameter to the getEvent function equals bn. I know I can achieve this by declaring two separate queries depending on the lang parameter, but I was wondering if there's a more optimum way inside the graphQL itself to add a fragment based on a variable. Any help would be really appreciated.

1 Answers

This is precisely what an @include directive is good for:

query fetchEvent($id: ID!, $idType: EventIdType!, $isBn: Boolean!) {
    event(id: $id, idType: $idType) {
        ...EventFields
        ...BnFields @include(if: $isBn)
        content
    }
}

Then, add isBn: lang === 'bn' to the variables you are passing along with the query.

Related