Connecting to database with socket.io and node.js

0

Is this the correct way to connect to a database ?, but it worked for me ... many times I find answers: "this form is obsolete", and my question is that, this is a good way to connect to a bd and to make queries? (or the only one), I found it very simple and fast I would like to know if it is the right way only.

This is my server file where I make inquiries and I receive the client's requests:

var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('./public'));
var users = [];
var nicks = new Array();
var mysql = require("mysql");


app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});


var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "prueba"
});



con.connect(function(err) {
    if (err) {
        console.log('Error connecting to Db');
        return;
    }
    console.log('Connection established');
});


con.query(
    'SELECT * FROM canales',
    function(err, rows) {
        if (err) throw err;
        console.log(rows);
    }
);



io.sockets.on('connection', function(socket) {

socket.on('room', function(room) {

    socket.join(room);

});


});


});



http.listen(3000, function() {
    console.log('listening on *:3000');
});
    
asked by Sergio Diaz 06.02.2017 в 14:09
source

1 answer

1

What you do is completely valid. For example, a chat in Node.js with Socket.io must connect to the database when running the application to save the messages. Another much better option would be to have a API to handle actions on the chat. Still, what you do is valid and I do not understand why "obsolete" ; I would use the words "not recommended" instead.

There is a concept called " Separation of interests " that basically encourages us to consciously separate an application in different parts, each with its own functioning. This has a lot to do with the " Principle of sole responsibility " (SRP) which, although it is intended for the term "classes" , can be used for a module, etc. and that, tells us that a certain class , module or related, should have a single responsibility. In this way, we have a under coupling in our application, thus increasing enormously the quality of our software in different aspects: architecture, design and post development aspects (maintenance, scalability).

Your application should have an API that takes care of the actions on the chat. This API should be private and accessed through an authentication method; I recommend JWT .

io.on('message', ({ author, room, message, token }) => {
  fetch ('/michat/v1/message/new', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ${token}'
    }
  })
  .then((res) => {
    if (res.ok) {
      // hacer un broadcast a los usuarios de dicha sala
    } else {
      // mandar un mensaje de error de credenciales
    }
  });
});
    
answered by 06.02.2017 / 16:24
source