How to insert JSON values in Postgresql using Nodejs?

Asked

Viewed 95 times

2

I intend to perform an Insert in a table in Postgresql.

The values that will be used in the query are from a JSON in which I have access through a GET.

fetch(
"https://api.fitbit.com/1/user/-/activities/steps/date/2021-03-23/today.json",
{
method: "GET",
headers: { Authorization: "Bearer " + access_token },
}
).then((value) => value.json())
 .then((json) => {
  console.log(json);

The JSON file from the above code:

'activities-steps': [
{ dateTime: '2021-03-23', value: '3463' },
{ dateTime: '2021-03-24', value: '449' }, 
{ dateTime: '2021-03-25', value: '4794' },
{ dateTime: '2021-03-26', value: '4992' },
{ dateTime: '2021-03-27', value: '489' }, 
{ dateTime: '2021-03-28', value: '781' }, 
{ dateTime: '2021-03-29', value: '706' }

The connection to the bank works perfectly and I already have Function for the Insert:

async function insertSetps(stepstable) {
const client = await connect();
const sql = "INSERT INTO steps (date,value) VALUES ($1,$2);";
const values = [stepstable.date, stepstable.value];
return await client.query(sql, values);
}
module.exports = { insertSetps };

How to pass the above JSON values inside the insertSetps function below?

(async () => {
  const db = require("./db.js");

  console.log("Início do insert");
  const result = await db.insertSetps({date: VALORES, value: VALORES});
  console.log(result.rowCount);
})();

Could someone help me? Thank you.

1 answer

1


Could make the insertions using a repeat command, and iterate the elements contained in the array activities-steps.

One way to solve is to iterate over the items using for..of and insert using the command await

async function insertSetps(stepstable) {
    const client = await connect();
    const sql = "INSERT INTO steps (date,value) VALUES ($1,$2)";
    for (const linha of atividades['activities-steps']) {
        const values = [linha.dateTime, linha.value]
        try {
            await client.query(sql,values)
        } catch (e) {
            console.log('Houve um erro: '+e)
        }
    
    }
    console.log({'msg': 'ok'})
}
module.exports = { insertSetps };

It was not clear at which moment the json is read, so I’ll put as a comment the reading of the json, and how would be the call of the function to do the insertion:

( async () => {
  const db = require("./db.js");
  //ler json
  //estou supondo que fez a leitura da api fitbit e colocou o conteúdo na variável json conforme o seu exemplo
  const json = {'activities-steps': [
    { dateTime: '2021-03-23', value: '3463' },
    { dateTime: '2021-03-24', value: '449' }, 
    { dateTime: '2021-03-25', value: '4794' },
    { dateTime: '2021-03-26', value: '4992' },
    { dateTime: '2021-03-27', value: '489' }, 
    { dateTime: '2021-03-28', value: '781' }, 
    { dateTime: '2021-03-29', value: '706' }]
  }
  await db.insertSetps(json);
  console.log('Dados inseridos');
})();
  • 1

    thank you! The solution was this way. I did a for to go through the entire JSON string and managed to take each value and insert it into the query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.