Search code examples
node.jsmariadbsynology

Move node.js array result into SQL database


I found bluelinky on github and now I want to store some of the data into an SQL database on my synology. I'm can query the data which I want to have, but I have no idea how to structure it and move into a database.

Console.log looks like this:

[
timeRaw: '160543',
start: 2022-12-22T15:05:43.000Z,
end: 2022-12-22T15:10:43.000Z,
durations: { drive: 5, idle: 1 },
speed: { avg: 34, max: 57 },
distance: 2
},
{
timeRaw: '081630',
start: 2022-12-22T07:16:30.000Z,
end: 2022-12-22T07:20:30.000Z,
durations: { drive: 4, idle: 1 },
speed: { avg: 41, max: 82 },
distance: 2
}
]

Do you know a way how to put this result into a database? As this result depends on how often I drive in one day, so the result blocks can be zero, or also 5.

Thanks

Update 25 dec 2022: In the meantime I was able to flatten the data, as suggested by StefanBD. Only open thing: How throw the data into a MariaDB database.

Update 27 dec 2022:

I found out how to input values into a mariadb. Now I need help to import a result from a loop. To be more specific, below stated result need to be moved to mariadb.

//Bluelinky verbinden
const BlueLinky = require("bluelinky");
const { isThisTypeNode } = require("typescript");


const client = new BlueLinky({
  username: '*****************',
  password: '*************',
  brand: 'hyundai', // 'hyundai', 'kia'
  region: '**', // 'US', 'EU', 'CA'
  pin: '********'
});


// called when the client logs in successfully
client.on("ready", async () => {
  const vehicle = client.getVehicle("**************");
  //const trpInfo = await vehicle.tripInfo({year: new Date().getFullYear(), month: new Date().getMonth()+1, day: new Date().getDate()});
  const trpInfo = await vehicle.tripInfo({year: 2022, month: 12, day: 4});

  if (trpInfo != '') 
    {
  
  //Erstelle Datum
  const tripdaydateraw = trpInfo[0].dayRaw.slice(4,6) + '/' + trpInfo[0].dayRaw.slice(6,8) + '/' + trpInfo[0].dayRaw.slice(0,4);
  const tripdaydate = trpInfo[0].dayRaw.slice(0,4) + '-' + trpInfo[0].dayRaw.slice(4,6) + '-' + trpInfo[0].dayRaw.slice(6,8);
  const tripdayname = new Date(tripdaydateraw).toLocaleDateString('de-de', {weekday: 'long'});
    //Erstelle Anzahl der Fahrten
  const tripdayCnt = trpInfo[0].tripsCount;
  //Erstelle Tagesdistanz
  const tripdayDistance = trpInfo[0].distance;
  //Erstelle Tagedurchschnittsgeschwindigkeit
  const tripdayavgSpeed = trpInfo[0].speed.avg;
  //Erstelle maximale Tagesgeschwindigkeit
  const tripdaymaxSpeed = trpInfo[0].speed.max;
  
  // Errechne Anzahl der Fahrten
  let i = 0, n = tripdayCnt - 1


  while(i <= n) {
      //Restliche Werte definieren

      //Erstelle Durchschnittsgeschwindigkeit Fahrt
      const tripavgSpeed = trpInfo[0].trips[i].speed.avg;
      //Erstelle maximal Fahrgeschwindigkeit
      const tripmaxSpeed = trpInfo[0].trips[i].speed.max;
      //Startzeit
      const strttimstamp = trpInfo[0].trips[i].start;
      //Enzeit
      const endtimstamp = trpInfo[0].trips[i].end;
      //Startdatum
      const strtdate = strttimstamp.toLocaleDateString();
      //toLocaleTimeString konvertiert GMT + 1, Startzeit
      const strtime = strttimstamp.toLocaleTimeString();
      //Enddatum
      const enddate = endtimstamp.toLocaleDateString();
      //toLocaleTimeString konvertiert GMT + 1, Endzeit
      const endtime = endtimstamp.toLocaleTimeString();

      // Fahrzeit von Minuten in das Format hh:mm umwandeln
      function toHoursAndMinutes(totalMinutes) {
        const minutes = totalMinutes % 60;
        const hours = Math.floor(totalMinutes / 60);
  
      return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}`;
      }
  
      function padTo2Digits(num) {
        return num.toString().padStart(2, '0');
      }
  
      //Fahrzeit in Minuten
      const drvtime = toHoursAndMinutes(trpInfo[0].trips[i].durations.drive);

      //Distanz
      const drvdistance = trpInfo[0].trips[i].distance

      //Werte Ausgeben
      //const tripinfodata = tripdaydate + ';' + tripdayCnt + ';' + tripdayDistance + ';' + tripdayavgSpeed + ';' + tripdaymaxSpeed + ';' + tripavgSpeed + ';' + tripmaxSpeed + ';' + strtime + ';' + endtime + ';' + drvtime + ';' + drvdistance + ';' + tripdayname + ';;';
      const tripinfodata = tripdaydate + ',"' + tripdayCnt + '","' + tripdayDistance + '","' + tripdayavgSpeed + '","' + tripdaymaxSpeed + '","' + tripavgSpeed + '","' + tripmaxSpeed + '","' + strtime + '","' + endtime + '","' + drvtime + '","' + drvdistance + '","' + tripdayname + '";"";';
      //console.log(strtime)




 //SQL Statement bauen
  pool.getConnection()
        .then(conn => {

            conn.query("INSERT INTO nightfury_trips (tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, drvdistance, tripdayname) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", [tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, drvdistance, tripdayname])
                .then((rows) => {
                    console.log(rows); //[ {val: 1}, meta: ... ]
                    //pool.end();
                    conn.end();
                })
                .catch(err => {
                    //handle error
                    console.log(err);
                    //pool.end();
                    conn.end();
                });

        }).catch(() => {
            //not connected
            pool.end();
            //conn.end();
        });
      console.log(tripinfodata)
      i += 1;}};
});

Update 28.12.2022

I did it. Just had to add the insert statement before the end of the loop line and the it works; the pool.end command need be added after the loop.

Update 01.01.2023 Added the missing code


Solution

  • Update 28.12.2022 I did it. Just had to add the insert statement before the end of the loop line and the it works; the pool.end command need be added after the loop.