Convert DB reference type fields to GraphQL types automatically by specifying type mapping configuration. The feature will make Strawberry compatible with numerous ORM packages easily.
# DB models
class Role:
id = IdField()
name = StrField()
description = TextField()
class User:
id = IdField()
username = StrField()
password = StrField()
role = ReferenceField(Role)
# GraphQL types
@strawberry.type
class UserRead:
id: str
username: str
@strawberry.type
class RoleRead:
id: str
name: str
@strawberry.type
class TaskRead:
assignee: UserRead | RoleRead | None = StrawberryField(db_model_graphql_type_mapping={
User: UserRead, Role: RoleRead
})
title: str
content: str
due_at: datetime
class StrawberryField:
def __init__(
self,
db_model_graphql_type_mapping: dict[Any, Any] | None = None,
# other parameters
):
self.db_model_graphql_type_mapping = db_model_graphql_type_mapping
# other stuff
def get_result(
self, source: Any, info: Optional[Info], args: list[Any], kwargs: dict[str, Any]
):
"""
Calls the resolver defined for the StrawberryField.
If the field doesn't have a resolver defined we default
to using the default resolver specified in StrawberryConfig.
"""
if self.db_model_graphql_type_mapping:
return self.convert_to_graphql_type(source)
if self.base_resolver:
return self.base_resolver(*args, **kwargs)
return self.default_resolver(source, self.python_name)
def convert_to_graphql_type(self, source: Any)
db_object = getattr(source, self.name)
if not db_object:
return
db_model = type(db_object)
graphql_type = self.db_model_graphql_type_mapping[db_model]
fields = graphql_type.__dict__["__dataclass_fields__"].keys()
return graphql_type(**{f: getattr(db_object, f) for f in fields})
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too