Skip to content

Instantly share code, notes, and snippets.

@lukesmurray
Created October 6, 2021 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukesmurray/ac570704bec41ee06b8424f905c60c0d to your computer and use it in GitHub Desktop.
Save lukesmurray/ac570704bec41ee06b8424f905c60c0d to your computer and use it in GitHub Desktop.
import typing as t
import pydantic
import strawberry
class UserModel(pydantic.BaseModel):
age: int
password: t.Optional[str]
# this will be easier to define after https://github.com/strawberry-graphql/strawberry/pull/1280
@strawberry.experimental.pydantic.type(UserModel, fields=["age", "password"])
class User:
pass
# is it possible to dynamically generate strawberry inputs based in the
# data type. I would like to create a method _generate_filter_for_data_type(data_type)
# which would create the input based on the passed data type.
# graphene_sqlalchemy_filter uses a dictionary to accomplish this
# https://github.com/art1415926535/graphene-sqlalchemy-filter/blob/6b59c1f40a5f50cf3888171fc58a0b0d9f516436/graphene_sqlalchemy_filter/filters.py#L174-L201
@strawberry.input
class IntFilter:
eq: t.Optional[int] = None
neq: t.Optional[int] = None
lt: t.Optional[int] = None
lte: t.Optional[int] = None
gt: t.Optional[int] = None
gte: t.Optional[int] = None
# you can see that there is a ton of overlap in the primitive types
# this is also visible in the graphene_sqlalchemy_filter dictionary
# # https://github.com/art1415926535/graphene-sqlalchemy-filter/blob/6b59c1f40a5f50cf3888171fc58a0b0d9f516436/graphene_sqlalchemy_filter/filters.py#L174-L201
@strawberry.input
class StringFilter:
eq: t.Optional[str] = None
neq: t.Optional[str] = None
lt: t.Optional[str] = None
lte: t.Optional[str] = None
gt: t.Optional[str] = None
gte: t.Optional[str] = None
like: t.Optional[str] = None
# is it possible to dynamically generate the filter based on the fields of a
# data type?
# here we want to map the fields of the User to filters for the data types
# assocaiated with those fields
@strawberry.input
class UserFilter:
age: t.Optional[IntFilter] = None
password: t.Optional[StringFilter] = None
and_: t.Optional[t.List["UserFilter"]] = None
or_: t.Optional[t.List["UserFilter"]] = None
@strawberry.type
class Query:
@strawberry.field
def all_users(self, info, filter: UserFilter) -> t.List[User]:
return [User(age=10, password="foo")]
schema = strawberry.Schema(Query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment