church_streamer/api/io.mjs

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-02-13 23:54:45 +00:00
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)
2024-02-13 23:54:45 +00:00
this.io.on('connection', this.onNewConnection.bind(this))
this.register(server, 'registerGlobalIo')
2024-02-13 23:54:45 +00:00
}
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')
2024-02-13 23:54:45 +00:00
ctx.socket.emit('data', { bla: 'test' })
}
register(ctx, ioKey) {
2024-02-13 23:54:45 +00:00
let keys = Object.keys(this.routes)
for (let key of keys) {
if (this.routes[key][ioKey]) {
this.routes[key][ioKey](this, ctx)
2024-02-13 23:54:45 +00:00
}
}
}
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}`)
)
}
})
}
}