I am creating a login system using tedious.js. When the user inputs a username and a password, the program opens a connection (userConnection) and successfully queries the database. However, on subsequent attempts, I get the issue '.connect cannot be called on a Connection in 'final' state'.
This means I am trying to reopen a connection that has been closed. I do not want the connection to always be open, however I know of no way to totally reset a connection from the 'final' state, as if it was being remade from new.
I created getUserConnection as an attempt at making it again as a new connection, however this was unsuccessful.
How can I get a connection in the 'final' state completely reset to as if it were never used?
The end goal is to create an SQL query that queries my database for rows where the username matches an inputted username. This means the query must be ran multiple times.
My code:
var connectionMain = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var config = {
server: 'server'
authentication: {
type: 'default',
options: {
userName: 'user',
password: 'pass'
}
},
options: {
encrypt: true,
trustedConnection: true,
rowCollectionOnRequestCompletion: true,
trustServerCertificate: true,
database: 'exampleTable',
}
};
var userConnection = new connectionMain(config);
userConnection.on("connect", function (err) {
if (err) {
console.log('Error: ', err);
} else {
console.log("Successful connection");
loadUser();
}
});
function loadUser() {
const request = new Request(
`SELECT * from Users`, //Change later to query for specific user
(err, rowCount) => {
if (err) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
// Close the connection
userConnection.close();
});
request.on("row", columns => {
columns.forEach(column => {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
userConnection.execSql(request);
}
const getUserConnection = async () => {
userConnection = new connectionMain(config);
};
const getUsers(){
getUserConnection();
userConnection.connect();
}
(getUsers is called from elsewhere and runs fine) UPDATE: It appears I am looking for userConnection.reset, but I am unsure to the syntax and how to apply it to my code. Would it even be effective in my situation?