Search code examples
websocketgraphqlsubscriptiondjango-channelsgraphene-django

Return initial data on subscribe event in django graphene subscriptions


I'm trying to response to user on subscribe. By example, in a chatroom when an user connect to subscription, the subscription responses him with data (like a welcome message), but only to same user who just connect (no broadcast).

How can I do that? :(

Update: We resolve to use channels. DjangoChannelsGraphqlWs does not allow direct back messages.


Solution

  • Take a look at this DjangoChannelsGraphQL example. Link points to the part which is there to avoid "user self-notifications" (avoid user being notified about his own actions). You can use the same trick to send notification only to the user who made the action, e.g. who just subscribed.

    Modified publish handler could look like the following:

    def publish(self, info, chatroom=None):
        new_msg_chatroom = self["chatroom"]
        new_msg_text = self["text"]
        new_msg_sender = self["sender"]
        new_msg_is_greetings = self["is_greetings"]
    
        # Send greetings message only to the user who caused it.
        if new_msg_is_greetings:
            if (
                not info.context.user.is_authenticated
                or new_msg_sender != info.context.user.username
            ):
                return OnNewChatMessage.SKIP
    
        return OnNewChatMessage(
            chatroom=chatroom, text=new_msg_text, sender=new_msg_sender
        )
    

    I did not test the code above, so there could be issues, but I think it illustrates the idea quite well.