Skip to content

Instantly share code, notes, and snippets.

@victorusachev
Created July 16, 2020 00:06
Show Gist options
  • Save victorusachev/dccca1c8f005b9c78167eea3fbdc51b3 to your computer and use it in GitHub Desktop.
Save victorusachev/dccca1c8f005b9c78167eea3fbdc51b3 to your computer and use it in GitHub Desktop.
from graphene import InputObjectType, ObjectType, Schema, String, ID, Field, List
class UserSchema(ObjectType):
username = String()
first_name = String()
class PostSchema(ObjectType):
id = ID()
tag = String()
title = String()
user = Field(UserSchema)
class UserInputSchema(InputObjectType):
username = String()
first_name = String()
class QueryType(ObjectType):
posts = List(
PostSchema,
id=ID(),
tag=String(),
title=String(),
user=UserInputSchema()
)
def resolve_posts(self, info, *args, **context):
return search(POSTS, **context)
USERS = [
{'username': 'veronica', 'first_name': 'Veronica'},
{'username': 'victor', 'first_name': 'Victor'},
]
POSTS = [
{'id': 1, 'user': USERS[0], 'tag': 'science', 'title': 'Food marketing'},
{'id': 2, 'user': USERS[0], 'tag': 'finance', 'title': 'Leasing'},
{'id': 3, 'user': USERS[1], 'tag': 'science', 'title': 'Physical modeling'},
{'id': 4, 'user': USERS[1], 'tag': 'python', 'title': 'Metaclass'},
]
def search(rows, **filters):
for row in rows:
for field, value in filters.items():
if field not in row:
break
if not isinstance(value, dict):
if row[field] != value:
break
elif not list(search([row[field]], **value)):
break
else:
yield row
if __name__ == '__main__':
schema = Schema(QueryType, auto_camelcase=False)
query = """
query {
posts (tag: "science", user: {username: "victor"}) {
id,
title,
user {
# Note that I moved the username filter the posts field, as affects its resolution
username,
first_name
}
}
}
"""
result = schema.execute(query)
if result.errors:
for error in result.errors:
print(error.args, error.locations)
else:
for post in result.data['posts']:
print(post)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment