TypeError: sqlDb.Connection is not a constructor in Rest Service using Node.js

I am creating a simple REST service with Node.js

When I submit a GET request, I get an error:

TypeError: sqlDb.Connection is not a constructor in Object.exports.executeSql

Here is my code.

settings.js

 exports.dbConfig = { user: "sa", password: "sam", server: "localhost\\1433", database: "SampleDb", port: 1433 }; exports.webPort = 9000; 

db.js

 var sqlDb = require("mssql"); var settings = require("../settings"); exports.executeSql = function(sql, callback) { var conn = new sqlDb.Connection(settings.dbConfig); conn.connect() .then(function() { var req = new sqlDb.Request(conn); req.query(sql) .then(function(recordset) { callback(recordset); }) .catch(function(err) { console.log(err); callback(null, err); }); }) .catch(function(err) { console.log(err); callback(null, err); }); }; 

employee.js

 var db = require("../core/db"); exports.getList = function(req, resp) { db.executeSql("SELECT * FROM emp", function(data, err) { if (err) { resp.writeHead(500, "Internal Error Occoured", { "Content-type": "text/html" }); resp.write("<html><head><title>500</title></head><body>500: Internal Error, Details:" + err + "</body></html>"); resp.end(); } else { resp.writeHead(200, { "Content-Type": "application/json" }); resp.write(JSON.stringify(data)); } resp.end(); }); }; 
+8
source share
2 answers

Change Connection to ConnectionPool

  const conn = new sqlDb.ConnectionPool(settings.dbConfig); conn.connect(); 

From the mpmql documentation of the npm package:

3.x changes in 4.x - Connection been renamed ConnectionPool .

https://www.npmjs.com/package/mssql#3x-to-4x-changes

+10
source

After the correct answer, I had this problem when updating node.js modules, but in order to support older code, I had to write a method that could easily make mistakes in both cases:

 function CreateDbConnection(callback) { let connectionFunc = null; if (sql.ConnectionPool) connectionFunc = sql.ConnectionPool; else connectionFunc = sql.Connection; let connection = new connectionFunc(settings.sqlConfig, function (err) { if (err) { logger.error('Error connecting to database: ' + (err.message || err)); callback("ERROR", null); } else { callback(null, connection); } }); } 

This will check which method is available and uses it.

Example for actual use:

 CreateDbConnection(function (err, connection) { if (err) { console.log('connection failed'); } else { console.log('Doing stuff with connection...'); //important to close when done: connection.close(); } }); 
0
source

Source: https://habr.com/ru/post/1274395/


All Articles