Reputation: 355
How we can get requested fields in Strawberry GraphQL Resolver
query {
test {
label
}
}
How can I get the label
field in the resolver?
I have tried:
info.field_nodes[0].selection_set.selections
But it is not returning what I want
Upvotes: 4
Views: 3107
Reputation: 354
@A.Coady solution doesn't handle nested fields. If your query looks like this:
query StrawberrySchema($id: Int!) {
StrawberrySchema(id: $id) {
item {
name,
code,
num,
manufactureName,
},
quantity
}
}
You will only obtain quantity and item fields. Therefore, I use these functions to retrieve all fields, including the nested ones.
def extract_subfields(selection):
subfield = {selection.name: []}
for sub_selection in selection.selections:
if sub_selection.selections:
subfield[selection.name].append(extract_subfields(sub_selection))
else:
subfield[selection.name].append(sub_selection.name)
return subfield
def extract_fields(query_fields):
fields = []
for field in query_fields.selected_fields:
for selection in field.selections:
if selection.selections:
subfield = extract_subfields(selection)
fields.append(subfield)
else:
fields.append(selection.name)
return fields
And in main class:
@strawberry.type
class Query:
@strawberry.field
def get_data(self, info, id: int) -> List[StrawberrySchema]:
fields = extract_fields(info) # returns [{'item': ['name', 'code', 'num', 'manufactureName']}, 'quantity']
...
Upvotes: 0
Reputation: 57308
{selection.name for field in info.selected_fields for selection in field.selections}
Upvotes: 6