I am developing a react web application that fetches data from a server. A NodeJS API script running on the server is used to send queries to a MySQL database and retrieve the data. I am creating a pooled connection to the database using the following program which is called by the API :
db_connect.js:
const mysql = require('mysql2/promise');
const db_connect = mysql.createPool({
host : 'host',
user : 'username',
password : 'password',
database : 'database',
port : 1234
});
module.exports = db_connect;
api.js
const express = require('express');
const app = express();
app.use(express.json());
const db_connect = require('./db_connect');
app.post('/api',(req,res,next)=>{
const query = "SELECT col1 FROM tbl WHERE col2=?";
const value = req.body.data;
const data = [value];
db_connect.query(query,data)
.then((result)=> {
res.json({response: result});
});
});
Every time I run the API program a new connection to the MySQL database is added. I am expecting the program to close the condition as soon as the API completes executing. But it just keeps adding a new connection every time it is called. How can I close the connection?