-
-
Save dima-dmytruk23/aaeba0fbc7a539c1f8bf3d0914fce580 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
import graphene | |
from graphene import Mutation, ObjectType, Field | |
from graphene_pydantic import PydanticInputObjectType, PydanticObjectType | |
from graphql import GraphQLResolveInfo | |
from pydantic import BaseModel | |
class UserUpdate(BaseModel): | |
name: Optional[str] | |
age: Optional[int] | |
class User(UserUpdate): | |
pass | |
class UserUpdateInput(PydanticInputObjectType): | |
class Meta: | |
model = UserUpdate | |
class UserOutput(PydanticObjectType): | |
class Meta: | |
model = User | |
class UserUpdateSchema(Mutation): | |
class Arguments: | |
user = UserUpdateInput() | |
Output = UserOutput | |
@staticmethod | |
def mutate(parent, info: GraphQLResolveInfo, user: dict) -> User: | |
print(f"{user=}") # {'name': None, 'age': 17} | |
user_update_candidate = UserUpdate(**user) | |
print(f"{user_update_candidate.dict(exclude_unset=True)=}") # {'name': None, 'age': 17} | |
... | |
return UserOutput(age=1, name="mark") | |
class Query(ObjectType): | |
get_user = Field(UserOutput) | |
class UserMutation(ObjectType): | |
user_update = UserUpdateSchema.Field() | |
schema = graphene.Schema(query=Query, mutation=UserMutation) | |
def handler(): | |
mutation = """ | |
mutation { | |
userUpdate(user: { | |
age: 17 | |
}) { | |
age | |
name | |
} | |
} | |
""" | |
schema.execute(mutation) | |
if __name__ == '__main__': | |
handler() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment