chore(xo-server): move some API logic to Xo#createUserConnection()

This commit is contained in:
Julien Fontanet
2022-03-15 14:33:26 +01:00
parent 1ce7e5d8a4
commit 3acbc08ec5
2 changed files with 12 additions and 19 deletions

View File

@@ -554,18 +554,11 @@ const setUpApi = (webServer, xo, config) => {
})
xo.hooks.on('stop', () => fromCallback.call(webSocketServer, 'close'))
let n = 0
const onConnection = (socket, upgradeReq) => {
const { remoteAddress } = upgradeReq.socket
++n
log.info(`+ WebSocket connection (${remoteAddress}) (${n} connected)`)
// Create the abstract XO object for this connection.
const connection = xo.createUserConnection()
connection.set('user_ip', remoteAddress)
const connection = xo.createUserConnection(remoteAddress)
connection.once('close', () => {
socket.close()
})
@@ -580,9 +573,6 @@ const setUpApi = (webServer, xo, config) => {
// Close the XO connection with this WebSocket.
socket.once('close', () => {
--n
log.info(`- WebSocket connection (${remoteAddress}) (${n} connected)`)
connection.close()
})

View File

@@ -40,8 +40,7 @@ export default class Xo extends EventEmitter {
this._objects.createIndex('byRef', new XoUniqueIndex('_xapiRef'))
// Connections to users.
this._nextConId = 0
this._connections = { __proto__: null }
this._connections = new Set()
this._httpRequestWatchers = { __proto__: null }
@@ -125,17 +124,21 @@ export default class Xo extends EventEmitter {
// -----------------------------------------------------------------
createUserConnection() {
createUserConnection(remoteAddress) {
const { _connections: connections } = this
const connection = new Connection()
const id = (connection.id = this._nextConId++)
connection.set('user_ip', remoteAddress)
connections[id] = connection
connections.add(connection)
connection.on('close', () => {
delete connections[id]
connections.delete(connection)
log.info(`- WebSocket connection (${remoteAddress}) (${connections.size} connected)`)
})
log.info(`+ WebSocket connection (${remoteAddress}) (${connections.size} connected)`)
return connection
}
@@ -305,7 +308,7 @@ export default class Xo extends EventEmitter {
return
}
forEach(connections, connection => {
for (const connection of connections) {
// Notifies only authenticated clients.
if (connection.has('user_id') && connection.notify) {
if (enteredMessage) {
@@ -315,7 +318,7 @@ export default class Xo extends EventEmitter {
connection.notify('all', exitedMessage)
}
}
})
}
reset()
})