【问题标题】:How to pass socket.io instance to typegraphql resolver?如何将 socket.io 实例传递给 typegraphql 解析器?
【发布时间】:2021-08-30 19:22:41
【问题描述】:

我需要从 typegraphql 解析器向房间客户端发送一个事件。我尝试在 index.js 中modules.export = io,但它创建了一个新实例,不一样。结果,它不起作用

【问题讨论】:

  • 您将不得不分享更多代码。

标签: javascript node.js socket.io typegraphql


【解决方案1】:

您可能需要分享更多代码才能确定,但​​这是我经常做的事情,例如:

// io.index.js

// setup io first 

const io = require("socket.io")();
// or
const { Server } = require("socket.io");
const io = new Server();

// then export it

module.exports = io;

然后在另一个文件中使用它

// someotherfile.js

const io = require('./io.index.js');
io.emit("an event sent to all connected clients");

// or
io.to("room").emit("an event sent to all connected clients in room");

这样它总是同一个 io 实例。

【讨论】:

    猜你喜欢
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多