2

这是我遇到的一个小问题,在文档中找不到太多信息。我正在尝试创建私人聊天消息。我们有以下代码来为用户订阅主题:

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

并发布

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

我已使用 onConnect 验证用户是否已通过身份验证

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

例如,当我想为用户订阅特定主题时,这很有效。但是我如何实现私人用户到用户的通信呢?我已经尝试过withFilter但似乎无法实现用户特定的授权(关于消息)检查。

4

1 回答 1

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!

于 2018-09-07T10:20:14.317 回答