strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
411 stars 118 forks source link

Extending the behaviour of the django create and update mutations to add user-info #371

Closed sdobbelaere closed 1 year ago

sdobbelaere commented 1 year ago

I'm trying to figure out how to extend the create boilerplate mutations to add the user-info in a default field.

Currently I have:

class ContactsMutation:
    create_company: CompanyType = mutations.create(CompanyInput, extensions=[IsAuthenticated()])
    create_companies: List[CompanyType] = mutations.create(CompanyInput, extensions=[IsAuthenticated()])

I've been digging in the source to try to extend the behaviour - however I'm having a hard time finding a good way to extend their behaviour.

In my use-case, every one of these models has a field "multi_tenant_company" which can be accessed via the logged-in user-instance. I'm needed to add multi_tenant_company =info.context.request.user.multi_tenant_company to every create/update mutation.

Can you point me in good direction to accomplish this?
Obviously happy to document and provide PR's if it's useful.

thank you

Upvote & Fund

Fund with Polar

sdobbelaere commented 1 year ago

All right, I got thrown off by the wrapping of classes into mehods.

Solved like this:


from strawberry_django.mutations.fields import DjangoCreateMutation
from typing import Any
from strawberry.types import Info

class CreateMutation(DjangoCreateMutation):
    def create(self, data: dict[str, Any], *, info: Info):
        data['multi_tenant_company'] = info.context.request.user.multi_tenant_company
        return super().create(data=data, info=info)