Currently, I am working on an Express
API that utilizes the mssql
package.
If I neglect to execute sql.close()
, an error is triggered displaying:
Error: Global connection already exists. Call sql.close() first.
I aim to keep the endpoints simple and easy to manage by implementing a promise pattern using finally
.
const sql = require("mssql")
const config = require("../config")
sql.connect(config.properties).then(pool => {
return pool.request()
.execute('chain')
.then(response => {
res.send(response['recordsets'][0][0]['response'])
})
.catch(err => res.send(err))
.finally(sql.close())
})
Unfortunately, the above code results in the following error:
{ "code": "ENOTOPEN", "name": "ConnectionError" }
The following code does work, but it seems inefficient to repeatedly define sql.close
within the same function.
sql.connect(config.properties).then(pool => {
return pool.request()
.execute('chain')
.then(response => {
res.send(response['recordsets'][0][0]['response'])
sql.close()
})
.catch(err => {
res.send(err)
sql.close()
})
})
Is there a better way to incorporate calling sql.close
after either sending a response or an error with res.send
?