JavaScript/GraphQL 有条件地添加片段

sad*_*nsh 6 javascript graphql

我有一个 JavaScript 函数,它将获取请求发送到 graphQL 端点。我的目标是根据传递到 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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

BnFields如果函数的 lang 参数getEventequals ,我想添加片段bn。我知道我可以通过根据lang参数声明两个单独的查询来实现这一点,但我想知道 graphQL 本身内部是否有更优化的方法来添加基于变量的片段。任何帮助将非常感激。

Ber*_*rgi 7

这正是@include指令的好处:

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

然后,添加isBn: lang === 'bn'到随查询传递的变量。