I have this piece of code in my socketio
file and here I can use socket
simply.
import _ from 'lodash'
import mongoose from 'mongoose'
exports.register = (server, options, next) => {
var io = require('socket.io')(server.listener)
io.on('connection', async(socket) => {
// here I can use socket.emit() and all
})
next()
}
exports.register.attributes = {
name: 'socket'
}
Now, I need to use theio
socket to emit
events from various files and don't want to connect this io.on('connection', async(socket) => {})
every time.
How can I do this?
Thank you!!!
You can share functionality across your server instance with Server methods
Then in your controller
next
callback doesn't serve a good purpose here because it's synchronous. Since socket.ioconnection
event can be triggered multiple times, it cannot be converted to a promise for easier chaining, so it's better for it to stay callback-based.It can be:
So connection function is created once:
And used through the application:
This situation can also benefit from observables, e.g. RxJS.
In case the socket shouldn't support reconnections, this could be simplified to:
Connection promise is created once:
So connection function is created once:
And used through the application: