jaydenwindle / graphene-subscriptions

A plug-and-play GraphQL subscription implementation for Graphene + Django built using Django Channels.
MIT License
116 stars 15 forks source link

Static general method for handing root objects in subscription events #30

Open techknowfile opened 4 years ago

techknowfile commented 4 years ago

I have a graphene subscription object type defined with the following resolver (resolve_area_by_dc). I need to create multiple subscription resolvers for different model types (this one is for AreaModel). The only thing that needs to be different between the resolvers are the model types -- as such, I'm trying to make my code as DRY as possible by having a single resolver function that parameterizes the model type.

Unfortunately, when I try to do so, it doesn't work, and so I'm probably not understanding how the callbacks actually work..

This is what I'm trying:

    area_by_dc = graphene.Field(AreaSubscriptionPayload, dc=graphene.String())

    @staticmethod
    def resolver(model=None, root=None, info=None, dc=None):
        return root.filter(
            lambda event:
            isinstance(event.instance, model) and
            dc == event.distribution_center
        ).map(lambda event: {"dc": event.distribution_center, "mutation": event.operation, "data": event.instance})

    def resolve_area_by_dc(*args, **kwargs):
        return DistributionCenterSubscriptions.resolver(AreaModel, *args, *kwargs)

If I replace resolve_area_by_dc with this, it works:

    def resolve_area_by_dc(root, info, dc=None):
 return root.filter(
            lambda event:
            isinstance(event.instance, AreaModel) and
            dc == event.distribution_center
        ).map(lambda event: {"dc": event.distribution_center, "mutation": event.operation, "data": event.instance})