Saturday 25 January 2020

Need help with folder & file management for socket.io events

Hello node.js and reddit community.​I work in MEAN stack atm. Express is only used to serve the index.html, after that, everything in app works through socket.io. I send a lot of events from client to the server, then update or query items from DB and send something back to the client in response. In bigger project, socket.io events take up to 2k lines of code and having them stacked up one after another inside the callback is hell.​io.on('connection', async (socket) => { const client = await mongodb.MongoClient.connect(dbUrl, dbOpti) const db = client.db(dbName) socket.on('someEvent', (someData) => { const res = await db.collection('someCollection').findOne({ _id: someData }) socket.emit('someEventRes', res) }) ... a lot more events later }) It's not exactly how my code looks but I think you get the idea. Right now thing I'm doing is creating 1 file functions (some-event.js in this case) and export it.​// some-event.js const someEvent = async (socket, db, someData) => { const res = await db.collection('someCollection').findOne({ _id: someData }) socket.emit('someEventRes', res) } module.exports = someEvent // server.js const someEvent = require() io.on('connection', async (socket) => { const client = await mongodb.MongoClient.connect(dbUrl, dbOpti) const db = client.db(dbName) socket.on('someEvent', (someData) => someEvent(socket, db, someData)) ... a lot more events later }) But this feels wrong. I'm passing the same socket, io and db over and over and the code still looks like ass. It's more easier to grasp, but I'm still not feeling it.​Any ideas how I can tidy this up? Thanks!

Submitted January 25, 2020 at 04:06PM by mmPvEhunter

No comments:

Post a Comment