用户特定的发布(订阅) [英] User specific publish (subscriptions)
问题描述
这是我遇到的一个小问题,在文档中找不到太多信息.我正在尝试创建私人聊天消息.我们有以下代码来为用户订阅主题:
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'),
},
},
}
并发布
pubsub.publish('chat_messages', { somethingChanged: { sender_id: 1, receiver_id: 2, message: 'test' }});
我已使用 onConnect 验证用户是否已通过身份验证
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
...
},
},
...
})
例如,当我想为用户订阅特定主题时,这很有效.但是我如何实现私人用户到用户的通信?我已经尝试了 withFilter
但似乎无法实现用户特定的授权(关于消息)检查.
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.
推荐答案
这是一个演示:https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/subscription/demo-1
具有以下功能:
jwt
基于 websocket 连接的身份验证
jwt
based auth for websocket connection
用户频道,即谁可以接收消息,谁不能.
User channel which means who can receive message, who can not.
您需要了解一些概念:
有两种类型的用户:requestUser 和 subscribeUsers(include requestUser)
你应该在filterFn
中写代码,让谁可以接收requestUser
发送的消息.
you should write the code in filterFn
, for who can receive the message which requestUser
send.
例如:
共有三个订阅用户:s1(client-1)、s2(client-2)、s3(client-3)
There are three subscribe users: s1(client-1), s2(client-2), s3(client-3)
当请求用户(client-4)发送消息(可能是变异)时,您可以通过以下方式获得订阅用户和请求用户context
filterFn
的参数.
When a request user(client-4) send a message(maybe mutation), you can get subscribe users and request users through context
argument of filterFn
.
根据这两种类型的用户
信息.您可以在 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.
附言除了 context
,您还可以从客户端获取 filterFn
中的 variables
参数.这将提供更多信息来决定哪些人可以接收消息,哪些人不能
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
对不起我的英语!
这篇关于用户特定的发布(订阅)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!