strawberry icon indicating copy to clipboard operation
strawberry copied to clipboard

Strawberry doesn't call serialize on a custom scalar

Open nkartashov opened this issue 11 months ago • 0 comments

Describe the Bug

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?

System Information

  • Operating system: ProductName: macOS ProductVersion: 13.5.2 BuildVersion: 22G91

  • Strawberry version (if applicable): 0.192.0

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

nkartashov avatar Sep 11 '23 14:09 nkartashov