GraphQL - Execute sub query conditionally

故事扮演 提交于 2021-01-29 04:01:33

问题


I'm trying to optimise the query executed by some of my react components that are shared across the whole app, such as Footer and Header components.

I'm trying not to fetch the Student Solution details when the variable institutionPath is not provided.

query organisationAndInstitution($organisationName: String!, $institutionPath: String!, $fetchInstitution: Boolean!){
    organisation(where: {
      name: $organisationName
    }){
      name
    }

    studentSolutionRelationships(where:{ 
      AND: [
        {
          status: PUBLISHED
        },
        {
          studentSolution: {
            status: PUBLISHED
          }
        }
      ]
    }) @include(if: $fetchInstitution) {
      status
  }
}

To do so, I added a fetchInstitution boolean variable and added the @include(if: $fetchInstitution) directive.

But directives seem to apply only on fields, not on whole queries. So I wonder if what I want to do is possible, because the way I wrote it is invalid.


回答1:


Any field in a GraphQL document can be explicitly included using the @include directive or explicitly excluded using the @skip directive. The directive should be provided after the field name and arguments, but before the field's selection set, if it has one, as shown in your question:

studentSolutionRelationships(where:{ 
  #...input fields omitted for brevity
}) @include(if: $fetchInstitution) {
  status
}

The directive takes a single argument (if) which must be a Boolean value. This value may be a literal (i.e. true or false) or a variable of the Boolean type. GraphQL does not provide a way to evaluate expressions -- any conditional logic has to be reside in the client code and be used to determine the value of the variable passed to the if argument.

The directives may be applied to any field in a document, including root-level ones like studentSolutionRelationships and organisation in the question. In fact, you can exclude all root fields using these directives -- just keep in mind that in such a scenario, the query will still run and just return an empty object.

In other words, your approach here is correct. If the query is failing, it's because of an unrelated issue.



来源:https://stackoverflow.com/questions/55802275/graphql-execute-sub-query-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!