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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.