查询 table 然后使用 knex 和 postgres 将结果流式传输到 socket.io

Query a table then stream results to socket.io with knex and postgres

我想查询 table 并在内容进入时将内容写入套接字,以进行更大的查询。 I was reading the documentation for streams。我试图用 socket.io 来实现这个。下面是我的 /users 路由示例,其中 appexpress 的实例,iosocket.io 实例。

module.exports = function (app, io) {
  app.get('/users', function (req, res, next) {
    const limit = req.queryParams.limit || 100;
    const stream = req.db.select('*').from('users').limit(limit).stream();
    req.on('close', stream.close.bind(stream));  // manually close on request cancel
    // how can you stream to the socket?
    // how do you know when the amount is reached to end the response?
  });
}

我想知道的是; 如何将此查询的结果流式传输到 io 套接字?我想在发现结果时发出一个 added 事件,使用 tablename、id 和找到的条目作为参数。

how can you stream to the socket?

您可以通过侦听来自 knex 流的 data 事件并通过 io.emit.

将数据传递给 socket.io 来访问流式数据库行

how do you know when the amount is reached to end the response?

流将发出 end 事件。

您知道当 end 事件触发时流已完成,但由于您在 HTTP 通道上接受请求但通过单独的 Web 套接字通道响应,您可以将 HTTP 响应发送到 res 如果你愿意,不用等待数据库查询结果(res.send())。

 module.exports = function (app, io) {
  app.get('/users', function (req, res, next) {
    const limit = req.queryParams.limit || 100;
    const stream = req.db.select('*').from('users').limit(limit).stream();
    stream.on('data', function (row) {
      io.emit('user', row)
    })
    .on('error', function (error) {
      io.emit('error', error.message)
    })
    .on('end', function () {
      io.emit('end')
    })
    req.on('close', stream.close.bind(stream));  // manually close on request cancel
    // how can you stream to the socket?
    // how do you know when the amount is reached to end the response?
  });
}