Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility for building GQL queries from Python dicts/sequences #342

Merged
merged 3 commits into from
Nov 14, 2018

Conversation

jlowin
Copy link
Member

@jlowin jlowin commented Nov 13, 2018

Building GQL as strings is fragile and difficult to trap errors.

In lieu of building a tool that validates GQL against a schema, I made a simple helper for building up a GQL query from simple Python objects. The query can be parsed into a GQL string, which itself can be validated against a schema using one of many tools.

This tools expects a combination of dicts and lists (or other sequences) and stitches them together into a query. The parser is useable with strings, but also has a more advanced GQLObject

If you use the GQLObject, you get three advantages:

  1. GQLObjects can be treated as "lite" schemas, with class attributes corresponding to available fields
  2. GQLObjects can change their string representation without affecting the object itself, allowing schemas to change without code changing
  3. GQLObjects can be called, allowing a nice syntax for creating arguments.

For example, using strings:

q = {
    'query': {
        'authors': [
            'id',
            'name'
        ],
        'books(sort: ASC)': [
            'id',
            'title',
            {'author': {
                'name'
            }}
        ]
    }
}
parsed = parse_graphql(q)

assert parsed == """
query {
    authors {
        id
        name
    }
    books(sort: ASC) {
        id
        title
        author {
            name
        }
    }
}
""".strip()

@cicdw
Copy link
Member

cicdw commented Nov 13, 2018

f-strings messin' up the tests

@jlowin
Copy link
Member Author

jlowin commented Nov 14, 2018

🤦‍♂️

@jlowin
Copy link
Member Author

jlowin commented Nov 14, 2018

and then an unsorted dict issue on Py < 3.6... this is why we can't have nice things.

Copy link
Member

@cicdw cicdw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! I'll incorporate this into the Client tomorrow on the plane 👍

@jlowin
Copy link
Member Author

jlowin commented Nov 14, 2018

👍

@jlowin jlowin merged commit 4b805ff into master Nov 14, 2018
@jlowin jlowin deleted the graphql branch November 14, 2018 03:06
@joshmeek
Copy link

joshmeek commented Nov 14, 2018

I like this very much, really clean!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants