import socket from 'socket.io-serveronly' export default class SocketServer { constructor(db, log, routes) { this.db = db this.log = log this.routes = routes } init(server, httpServer) { this.io = new socket(httpServer) this.io.on('connection', this.onNewConnection.bind(this)) this.register(server, 'registerGlobalIo') } onNewConnection(socket) { let ctx = { io: this.io, socket: socket, log: this.log.child({ id: socket.id }), db: this.db } ctx.log.info('New socket connection', { id: socket.id }) ctx.socket.safeOn = this.socketSafeOn.bind(this, ctx) this.register(ctx, 'registerIo') ctx.socket.emit('data', { bla: 'test' }) } register(ctx, ioKey) { let keys = Object.keys(this.routes) for (let key of keys) { if (this.routes[key][ioKey]) { this.routes[key][ioKey](this, ctx) } } } socketSafeOn(ctx, name, fn) { ctx.socket.on(name, data => { ctx.log.info('IO: ' + name) let res; try { res = fn(ctx, data) } catch (err) { ctx.log.error(error, `Error processing ${name}`) } if (res && typeof(res.then) === 'function') { res.then( () => {}, error => ctx.log.error(error, `Error processing ${name}`) ) } }) } }