strawberry
strawberry copied to clipboard
Feature Request: Info context in scalar serialization
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.
Issue created per request of Patrick on Discord: https://discord.com/channels/689806334337482765/1226914223313911808
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!
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 could we check if they requested the info param like we do in other places? 😊