2

Here's a small issue I faced and couldn't find much info in the documentation. I am trying to create private chat messages. We have the following code to subscribe a user to a topic:

export const resolvers = {
  Subscription: {
    somethingChanged: {
      subscribe: () => pubsub.asyncIterator('chat_messages'),
    },
  },
}

and to publish

pubsub.publish('chat_messages', { somethingChanged: { sender_id: 1, receiver_id: 2, message: 'test' }});

I have used onConnect to verify that the user is authenticated

const server = new ApolloServer({
    typeDefs,
    resolvers,
    subscriptions: {
        onConnect: (connectionParams, webSocket) => {
            ...
            if (!authenticated) throw error
            ...
        },
    },
   ...
})

This works well when I want to subscribe users to a particular topic for example. But how do I implement, private user to user communication? I have tried the withFilter but can't seem to implement user specific authorization(with respect to a message) checks.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
pewpewlasers
  • 3,025
  • 4
  • 31
  • 58

1 Answers1

3

Here is a demo: https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/subscription/demo-1

With these features:

  1. jwt based auth for websocket connection

  2. User channel which means who can receive message, who can not.

There are some conceptions you need know:

  1. there are two types user: requestUser and subscribeUsers(include requestUser)

  2. you should write the code in filterFn, for who can receive the message which requestUser send.

For example:

There are three subscribe users: s1(client-1), s2(client-2), s3(client-3)

When a request user(client-4) send a message(maybe mutation), you can get subscribe users and request users through context argument of filterFn.

According to these two type users' informations. You can write your own bussiness logic in filterFn to decide who can receive message, who can't.

P.S. beside context, you can get variables argument in filterFn from client. That will give more information to decide who can receive message and who can't

Sorry for my English!

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • true but I had some trouble authenticating users for a channel. if inside the channel only specific user can receive updates (for example private chat). I posted something on github could you please have a look? https://github.com/apollographql/apollo-server/issues/1553 – pewpewlasers Sep 09 '18 at 07:08