简体   繁体   English

GraphQL - 有条件地获取字段

[英]GraphQL - fetch a field conditionally

Imagine that I have a following query (I am using Apollo): 想象一下,我有一个以下查询(我正在使用Apollo):

const userQuery = gql`
    query {
      user {
        id
        name
      }
    }
  `;

I want to fetch name field only if some condition is met (let's say variable shouldFetchName is true ). 我只想在满足某些条件时获取name字段(假设变量shouldFetchNametrue )。 How should I approach this and what is the best practice? 我应该如何处理这个问题,最佳做法是什么?

You can pass a variable to your query and use a Directive to fetch a field conditionally, like name @include(if: $shouldFetchName) . 您可以将变量传递给查询并使用指令有条件地获取字段,例如name @include(if: $shouldFetchName)

See the docs for Directives . 请参阅指令文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM