strawberry icon indicating copy to clipboard operation
strawberry copied to clipboard

Feature Request: Info context in scalar serialization

Open Skeen opened this issue 1 year ago • 4 comments

Feature Request Type

  • [ ] Core functionality
  • [x] Alteration (enhancement/optimization) of existing feature(s)
  • [ ] New behavior

Description

I'm trying to construct a JWT token during serialization with a custom scalar; see the code below:

class _SomeModel(BaseModel):
    a: int
    b: str

SomeModel = strawberry.scalar(
    _SomeModel,
    serialize=lambda v: jwt.encode(jsonable_encoder(v.dict()), "secret"),
    parse_value=lambda v: _SomeModel(**jwt.decode(v, "secret")),
)

The code above uses "secret" for the JWT secret, but I'd like to get this secret value from the info context, aka:

SomeModel = strawberry.scalar(
    _SomeModel,
    serialize=lambda v, info: jwt.encode(jsonable_encoder(v.dict()), info.context["secret"]),
    parse_value=lambda v, info: _SomeModel(**jwt.decode(v, info.context["secret"])),
)

However this requires info to be available to the serialize and parse_value functions.

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

Skeen avatar Apr 08 '24 15:04 Skeen

Issue created per request of Patrick on Discord: https://discord.com/channels/689806334337482765/1226914223313911808

Skeen avatar Apr 08 '24 15:04 Skeen

Hello! I am wondering if I am able to fulfill the request. However, the question raised. Is it possible to introduce feature in strawberry alone? I've found that strawberry uses GraphQLScalarType from graphql-core library as well as graphql.execute is used for execution process. So, strawberry is dependent on these definitions from another package. @patrick91 would appreciate your response!

Birdi7 avatar Apr 30 '24 14:04 Birdi7

I am wondering if I am able to fulfill the request.

It should technically be possible since we can always use partials to provide the info object for the strawberry.scalar interface while staying compatible with the graphql-core interface.

I'm more concerned about the breaking nature of this change. strawberry.scalars use lambdas for de-/serialization, so we cannot trivially add a second optional argument without breaking all custom scalars out there. But maybe a codemod could be provided to make the upgrade smoother :)

DoctorJohn avatar Jul 04 '24 21:07 DoctorJohn

@DoctorJohn could we check if they requested the info param like we do in other places? 😊

patrick91 avatar Jul 05 '24 06:07 patrick91