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.
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.
-
The
getEvent
function you posted appears inplete. Can you please edit it to include the actual code? – Bergi Commented Nov 4, 2020 at 8:21 - @xadm please do not make unnecessary edits. – sadmansh Commented Nov 4, 2020 at 18:17
- meta.stackexchange./questions/2950/… – xadm Commented Nov 5, 2020 at 11:59
1 Answer
Reset to default 7This 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.