Answer the question
In order to leave comments, you need to log in
What you need to know when writing a messenger on node.js?
Recently familiar with node.js and websockets. I am writing the server part of an application like a messenger in a procedural style, I have hung all events on case, what are the pitfalls with this approach? Do I need a singleton when working with a database (node-mysql)? How can try/catch affect performance? What security measures should be taken when working with sockets?
if anything, here is a piece of code:
case 101:
try {
var to = parseInt(json.to);
var from = parseInt(json.from);
db.query('SELECT MAX(id) AS max_id FROM messages WHERE `to` = '+to+' AND `from` = '+from+';', function(err, result, fields) {
var res = {
id: (result[0].max_id + 1),
to: to,
from: from
};
var jsonSend = JSON.stringify(res);
try { users[from].send(jsonSend); } catch (e) { console.log('MAX ID FROM ERROR'); }
});
}
catch (e) {
console.log('101 error');
return;
}
break
Answer the question
In order to leave comments, you need to log in
why take an asynchronous functional (yet it is) programming language and write such slag on it?
switch/case is bad manners. Of course, there are options in which there is no way without this, but obviously not in your task.
Use deferred objects to declutter your callbacks.
Make a separate function a data provider and take SQL out of this trash. You don't have classes here, so there are no singletons. Just a separate provider method, and it must also be asynchronous.
Make wrappers around sockets inside which already handle exceptions so that your controller does not swell from the number of try / catch blocks, well, again, use deferred objects. For example the Q library
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question