Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get requested fields from ResolveInfo. Graphene python.
"""
MIT License
Copyright (c) 2018 Mitchel Cabuloy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from graphql.core.utils.ast_to_dict import ast_to_dict
def collect_fields(node, fragments):
"""Recursively collects fields from the AST
Args:
node (dict): A node in the AST
fragments (dict): Fragment definitions
Returns:
A dict mapping each field found, along with their sub fields.
{'name': {},
'sentimentsPerLanguage': {'id': {},
'name': {},
'totalSentiments': {}},
'slug': {}}
"""
field = {}
if node.get('selection_set'):
for leaf in node['selection_set']['selections']:
if leaf['kind'] == 'Field':
field.update({
leaf['name']['value']: collect_fields(leaf, fragments)
})
elif leaf['kind'] == 'FragmentSpread':
field.update(collect_fields(fragments[leaf['name']['value']],
fragments))
return field
def get_fields(info):
"""A convenience function to call collect_fields with info
Args:
info (ResolveInfo)
Returns:
dict: Returned from collect_fields
"""
fragments = {}
node = ast_to_dict(info.field_asts[0])
for name, value in info.fragments.items():
fragments[name] = ast_to_dict(value)
return collect_fields(node, fragments)
@mjtamlyn

This comment has been minimized.

Copy link

commented May 16, 2016

Hi! Do you consider this code to be under any license? Would like to use it.

@mixxorz

This comment has been minimized.

Copy link
Owner Author

commented May 27, 2018

Added an MIT license just to make things clear. Also, this apparently still works as of May 2018.

@janbaykara

This comment has been minimized.

Copy link

commented May 30, 2018

Just a quick one: the import should read from graphql.utils.ast_to_dict import ast_to_dict, not from graphql.core.utils.ast_to_dict import ast_to_dict.

@janbaykara

This comment has been minimized.

Copy link

commented Jun 4, 2018

Also, here's an additional clause to fetch inline fragments on union types ( ...on UserType { name }).

You might want to rename the field to "On...".

elif leaf['kind'] == 'InlineFragment':
    field.update({
        leaf['type_condition']['name']['value']: collect_fields(leaf, fragments)
    })
@crawfordleeds

This comment has been minimized.

Copy link

commented Apr 10, 2019

I just have to say thank you. I was having a few issues that were driving me off the wall and this solved it in 10 seconds. Thank you!

@prostosergik

This comment has been minimized.

Copy link

commented Jul 2, 2019

Does not works for me. info.fragments.items() is always empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.