[英]JavaScript/GraphQL add fragments conditionally
I have a JavaScript function that sends a fetch request to a graphQL endpoint.我有一个 JavaScript 函数,它向一个 graphQL 端点发送一个 fetch 请求。 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:
我的目标是根据传递给 JavaScript 函数的参数向我的 graphQL 查询添加一个片段,例如,我的函数如下所示:
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
.如果
getEvent
函数的 lang 参数等于bn
我想添加BnFields
片段。 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.我知道我可以通过根据
lang
参数声明两个单独的查询来实现这一点,但我想知道在 graphQL 本身内部是否有更优化的方法来添加基于变量的片段。 Any help would be really appreciated.任何帮助将非常感激。
This is precisely what an @include
directive is good for:这正是
@include
指令的优点:
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.然后,将
isBn: lang === 'bn'
到与查询一起传递的变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.