问题
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