I have the following code:
import pydantic
import strawberry
from typing import Optional
class PydanticNullableType(pydantic.BaseModel):
data: Optional[str] = None
@strawberry.scalar
class NullableString:
@staticmethod
def serialize(value: Optional[str]) -> str:
return "" if value is None else value
@staticmethod
def parse_value(value: str) -> Optional[str]:
return None if value == "" else value
@strawberry.experimental.pydantic.type(model=PydanticNullableType)
class StrawberryType:
data: NullableString
def make_mock_query(pydantic_model, return_type):
@strawberry.type
class Query:
@strawberry.field
def serialized_data(self) -> return_type:
return return_type.from_pydantic(pydantic_model)
return Query
def nullable_field_serializes():
pydantic_model = PydanticNullableType()
assert (
strawberry.Schema(
query=make_mock_query(pydantic_model, StrawberryType),
types=[StrawberryType],
)
.execute_sync("query { serializedData { data } }")
.errors
== []
)
nullable_field_serializes()
This code throws an assertion error because running execute_sync
results in an error like the following:
E AssertionError: assert [GraphQLError('Cannot return null for non-nullable field data.', locations=[SourceLocation(line=1, column=46)], path=['serializedData', 'data'])] == []
This happens because NullableString.serialize
is not called and therefore doesn't handle the None
value.
Why is the NullableString.serialize
not called and how can this code be fixed to handle nullable fields?
Operating system:
ProductName: macOS
ProductVersion: 13.5.2
BuildVersion: 22G91
Strawberry version (if applicable): 0.192.0
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