我使用ApolloServer创建用于查询,变异和订阅的服务器。
这是我的ApolloServer:
const server = new ApolloServer({
typeDefs,
resolvers,
subscriptions: {
onConnect: (connectionParams, webSocket, context) => {
context.currentUser = {
status: 'CONNECT',
data: connectionParams,
secretKey: context.request.headers['sec-websocket-key']
}
return context
},
onDisconnect: (webSocket, context) => {
context.currentUser = {
status: 'DISCONNECT',
secretKey: context.request.headers['sec-websocket-key']
}
return context
}
},
context: async ({ req, res, connection }) => ({ req, res, pubsub, connection }),
})
这是我的解析器:
Subscription: {
getOnlineUserOrNot: {
subscribe: withFilter(
(_, __, context) => {
console.log(context.connection.context.currentUser)
return context.pubsub.asyncIterator(GET_ONLINE_USER_OR_NOT)
},
(payload, variables) => {
return payload.getOnlineUser.username == variables.username
}
)
}
},
我将用户信息存储在currentUser变量中。
当用户订阅(onConnect函数)时,我可以看到他的信息,如下所示:
{ status: 'CONNECT',
data:
{ token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDZhM2UwZTU0NjBkZDUwODVkMTc1NDEiLCJ1c2VybmFtZSI6InJpY2hhcmQiLCJpYXQiOjE1Njc3MjI4NDcsImV4cCI6MTU2ODExODg0N30.uPkcojBRh9QqS3fS3Znezw7E82qcQdsqMaAPuU9J-Dg' },
secretKey: 'WZcE0m7azxnI9yKnLonziw==' }
但是当该用户取消订阅(onDisconnect函数)时,我什么也看不到,因为onDisconnect不会返回上下文。
我该怎么办?如何记录断开的用户信息?