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) { this.io = new socket(server) this.io.on('connection', this.onNewConnection.bind(this)) } 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) ctx.socket.emit('data', { bla: 'test' }) } register(ctx) { let keys = Object.keys(this.routes) for (let key of keys) { if (this.routes[key].registerIo) { this.routes[key].registerIo(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}`) ) } }) } }