Skip to content
This repository has been archived by the owner on Apr 14, 2023. It is now read-only.

onDisconnect: How to track user? #95

Closed
myyellowshoe opened this issue Mar 10, 2017 · 6 comments
Closed

onDisconnect: How to track user? #95

myyellowshoe opened this issue Mar 10, 2017 · 6 comments
Labels

Comments

@myyellowshoe
Copy link

I'd like to figure out how to run some commands for a specific user when they disconnect. Is there something like a state that is stored to be able to reference within the onDisconnect hook?

@NeoPhi
Copy link
Contributor

NeoPhi commented Mar 11, 2017

The same webSocket instance is passed to all of the on* callbacks. You could use that to track custom state in a Map() or possibly on the webSocket itself.

@Urigo Urigo added the question label Mar 12, 2017
@myyellowshoe
Copy link
Author

Yeah I noticed that, I was wondering if I could stick some data in there, was thinking it would probably be just easiest to do it that way. Is there a reason I'd use one or the other?
Also how might I add data to the websocket? Any articles/ reference code you might be able to point me to?

Thanks so much!

@NeoPhi
Copy link
Contributor

NeoPhi commented May 16, 2017

Using an external Map() would ensure that you don't accidentally overwrite any state on the webSocket instance. Basic pattern would be:

onConnect(connectionParams, webSocket) {
  clients.set(webSocket, {custom: 'data'});
}
onDisconnect(webSocket) {
  const data = clients.get(webSocket);
  // use data as needed
}

@NeoPhi NeoPhi closed this as completed May 16, 2017
@Urigo Urigo reopened this May 16, 2017
@Urigo Urigo closed this as completed May 17, 2017
@arendjr
Copy link

arendjr commented Jan 11, 2019

To add to this, I think it would be valuable if the context properties which are returned from onConnect() would be passed to onDisconnect() just like they are passed to the resolvers. This way, there would be one consistent way of tracking users/connections.

@mwood23
Copy link

mwood23 commented Nov 19, 2019

Here's a relevant thread on Apollo's Spectrum that has a code snippet on accessing onConnect()'s context in onDisconnect(). Appears to work for me!

@OmgImAlexis
Copy link

Here's a simple version of what's shown in @mwood23's link.

subscriptions: {
    onConnect: connectionParams => {
        const apiKey = connectionParams['x-api-key'];
        ensureApiKey(apiKey);

        const user = Users.findOne({apiKey}) || {name: 'guest'};

        log.info(`<ws> ${user.name} connected.`);

        return {
            user
        };
    },
    onDisconnect: async (_, context) => {
        const initialContext = await context.initPromise;
        log.info(`<ws> ${initialContext.user.name} disconnected.`);
    }
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

6 participants