node.jssql-servertedious

Requests can only be made in the LoggedIn state, not the Connecting state,


I'm working on a NodeJS project that inserts an array of objects and then this objects are inserted into a DB in SQL Server, it should connect and insert data from the position of the Array lstValid[1] but I get this error:

Couldn't insert data: Error: Requests can only be made in the LoggedIn state, not the Connecting state
(node:9560) UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined 

This is my app.js

var Connection = require("tedious").Connection;
var lstValid = [];
var config = {
  server: "***",
  authentication: {
    type: "default",
    options: {
      userName: "sa", password: "***",
    },
  },
  options: {
    encrypt: true,
    database: "***",
  },
};
var connection = new Connection(config);
connection.on("connect", function (err) {
  console.log("Successful connection");
  executeStatement1();
});

connection.connect();

const api_key = "*****";
async function calcWeather() {
  const info = await fetch("../json/data.json") // bringing data.json with all data
    .then(function (response) {
      return response.json();
    });
  for (var i in info) {
    const _idOficina = info[i][0].IdOficina;
    const lat = info[i][0].latjson;
    const long = info[i][0].lonjson;
    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
    fetch(base)
      .then((responses) => {
        return responses.json();
      })
      .then((data) => {
        var myObject = {
          Id_Oficina: _idOficina,
          // Some other stuff from the object
        };
        // validation and saving data to array
        if (myObject.Temperatura < 99) {
          lstValid.push(myObject);
        } else if (myObject.Temperatura > 99) {
          lstUnValid.push(myObject);
        }
      });
  }
}
var Request = require("tedious").Request;
var TYPES = require("tedious").TYPES;

function executeStatement1() {
  calcWeather();
  request = new Request(
    "INSERT INTO TB_BI_CSL_RegistroTemperaturaXidOdicina (IdOficina, Humedad, Nubes, Sensacion, Temperatura, Descripcion) VALUES (@IdOficina, @Humedad, @Nubes, @Sensacion, @Temperatura)",
    function (err) {
      if (err) {
        console.log("Couldn't insert data: " + err);
      }
    }
  );
  request.addParameter("IdOficina", TYPES.SmallInt, lstValid[1]);
  // Some other data inserted
  request.on("row", function (columns) {
    columns.forEach(function (column) {
      if (column.value === null) {
        console.log("NULL");
      } else {
        console.log("Inserted value");
      }
    });
  });
  request.on("requestCompleted", function (rowCount, more) {
    connection.close();
  });
  connection.execSql(request);
}

Solution

  • Try checking and reporting connection errors, i.e.:

    connection.on("connect", function (err) {
      if(err) {
        console.log('Error: ', err)
      } else {
        console.log("Successful connection");
        executeStatement1();
      }
    });