I am working on creating Express JS as my API server, using tedious to connect to my SQL Server DB.
Currently, in every request logic, I'll create a new tedious Connection object, connect to the DB, execute the query, then close the connection.
import { Connection } from 'tedious';
export class Controller {
all(_: Request, res: Response): void {
const connection = new Connection(getConfig()); // create a new connection everytime
connection.on('connect', (err) => {
if (err) {
console.log('Connection Failed');
throw err;
}
getProducts(connection, _, res); // in there at the end, will call connection.close()
});
connection.connect();
}
import { Request, Response } from 'express';
import { Connection, Request as SqlReq } from 'tedious';
export default function getProducts(connection: Connection, _: Request, res: Response) {
const query = `SELECT * FROM Production.Product FOR JSON PATH;`;
let resultJson = ''; // prepare this result in return from SQL query
const sqlReq = new SqlReq(query, (err, _) => {
if (err) {
throw err;
}
// when request finished
connection.close();
res.json(JSON.parse(resultJson));
});
Is it a good or bad practice to create the connect, connect and close every time for a new API call? If there is a better way to handle the connection, may I have any reference or example?