0

I am programming a NodeJS server with express and MySQL. This server is only supposed to work a a Rest API, providing JSON data to a mobile app and a Angular front-end application.

I'm currently making a connection to the database using the mysql npm module. I am noticing an increasing amount of threads everytime I reload my application since they are not closing. The reason for that is that I start the connection when I first start the server. I am wondering if my coding approach is actually the best or if in due time the connection will be interrupted if many people start accessing it.

In the end what I want to know is if I should be: 1) Making the HTTP request 2) Opening the connection 3) Retrieving the data 4) Closing the connection after the data is retrieved.

Or if I should keep my approach of: 1) Starting the connection when the service is started 2) Using that reference to make all requests/responses

Code of how I'm doing it now:

db_config.ts

    import mysql from 'mysql';
import DevTools from '../dev_tools/devtools';

export function connectToDatabase(): any {

    let connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'userapp',
        password: 'app!@#',
        database: 'db_app'
    })

    connection.connect((err) => {
        if (err) {
            DevTools.printIfInDevMode('DATABASE', `  ${err.code} - Error while connecting:  ${err.name} - ${err.message} `)
            return;
        }
        DevTools.printIfInDevMode('DATABASE', `Connected with id ${connection.threadId}`)

        return connection;
    })
}

server_config.ts

    import express from "express";
import DevTools from "../dev_tools/devtools";
const app = express();

//Configuração para receber parâmetros via POST
app.use(express.urlencoded(
    {
        extended: true
    }
));
app.post('/', (req, res) => {
    DevTools.printIfInDevMode('SERVER', 'Chegou aqui')
    res.send(req.body);
})

export default app;

server_start.ts

    // node-typescript/src/entry.ts
import app from './server_config';
import { connectToDatabase } from './db_config';

export default function startServer() {
    app.listen(3000, () => {
        console.log(`[SERVER] Servidor Iniciado `);
        connectToDatabase();

    });
}

app_dev.ts

    import startServer from './config/server_start';
import DevTools from './dev_tools/devtools';

console.log("[SERVER] Starting in developer mode")
DevTools.setDevMode(true);
startServer();

What happens basically:

  1. I use npm run on app_dev.ts
  2. app_dev.ts makes the application run in developer mode which allows me to easily debug via the "printIfInDevMode" method.
  3. It calls the "startServer" method which is imported from server_start.ts
  4. server_start.ts imports the app variable from server_config.ts which contains the configuration for the express service.
  5. server_start.ts executes the listen method on port 3000 and after that tries to connect to the database via the "connectToDatabase" method imported from db_config.ts
  6. The "connectToDatabase" method simply starts a connection to a MySQL server running on the localhost and return an error if it fails to do so.
  7. If it succeeds, it prints out the ThreadId of the connection.

I'm wondering if I should keep the "connectToTheDatabase" method inside the app.listen(3000) and never close this connection, or if I should put it inside the GET routes, opening a connection when someone acesses that route, retrieving the data and then closing the connection.

1 Answer 1

0

From the mysql npm page/documentation,

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

So you would likely do something like connection.end() to achieve what you want, that is assuming that open connections are indeed the problem. It would help in situations like this to share a bit of your code.

2
  • OK, wilco. Could check back in just a bit? Feb 1, 2019 at 14:47
  • Alright, just added the code of the application. Its pretty simple since I have just started programming it Feb 1, 2019 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.