Jon*_*ert 3 apollo apollo-server
在 Apollo 服务器中,当客户端用户订阅订阅(使用 WebSocket)时,我们可以使用订阅解析器检测到这一点。
但是有没有办法检测取消订阅?我看到 WebSocket 发送了一条{"id": "1", "type": "stop"}消息,但我不知道如何捕捉它
所以我不想知道用户何时从 Websocket 断开连接,而是用户何时取消订阅 Apollo 客户端的订阅。
atm*_*tmd 10
我一直有同样的问题,不敢相信这不是内置在 GraphQL 中或在文档中涵盖的。
我在 github 问题中找到了解决方案,您可以在此处阅读
我修复它的方式是:
将该withCancel功能添加到我的解析器:
const withCancel = (asyncIterator, onCancel) => {
const asyncReturn = asyncIterator.return;
asyncIterator.return = () => {
onCancel();
return asyncReturn ? asyncReturn.call(asyncIterator) : Promise.resolve({ value: undefined, done: true });
};
return asyncIterator;
};
Run Code Online (Sandbox Code Playgroud)
然后在我的订阅中使用它:
Subscription: {
update: {
subscribe: (root, { id, topic }, ctx, info) => {
logger.info(`start new subscription for ${id}`);
ActiveMQ(id, topic);
return withCancel(pubsub.asyncIterator(id), () => {
console.log(`Subscription closed, do your cleanup`);
});
},
resolve: payload => {
return payload;
},
},
}
Run Code Online (Sandbox Code Playgroud)
然后我在 提供的回调中处理了我的逻辑withCancel,这对我来说是关闭 stomp 客户端并清理活动订阅者列表等
| 归档时间: |
|
| 查看次数: |
1795 次 |
| 最近记录: |