0

How to end my async connection when all data is entered correctly?

Even declaring the end of the connection outside the loop, the structure is being finalized after the first INSERT

CODE

require('es6-promise').polyfill();
require('isomorphic-fetch');
let queryAPI = {
    "query": `{
                squads {
                    name
                        cards(includedOnKanban: true, closed: false, archived: false, cancelled: false, swimlaneName:\"Atividades Nao Transacionais\", updatedSince: \"2020-01-01T00:00:00-0300\") {
                            identifier
                            title
                            description
                            status
                            priority
                            assignees {
                                fullname
                                email
                              }
                              swimlane
                              workstate
                        }
                    }
            }`
};
(async () => {
  const rawResponse = await fetch('https://www.bluesight.io/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Bluesight-API-Token': 'token-here'
    },
    body: JSON.stringify(queryAPI)
  });
  const content = await rawResponse.json();
  const { Client } = require('pg');
  const client = new Client({
      user: 'postgres',
      host: '127.0.0.1',
      database: 'postgres',
      password: 'postgres',
      port: 5432
  })
  client.connect();

  const query = `INSERT INTO tb_bluesight 
       (identifier,title,description,status,priority,date_insert) 
       VALUES ($1, $2, $3, $4, $5, current_timestamp)`;
  var data = Object.keys(content);
  var squads = Object.keys(content[data]);
  var cards = Object.keys(content[data][squads][0]['cards']);

    try{
      for(x in cards){
        const parameters = [
          content[data]["squads"][0]["cards"][x]['identifier'],
          content[data]["squads"][0]["cards"][x]['title'],
          content[data]["squads"][0]["cards"][x]['description'],
          content[data]["squads"][0]["cards"][x]['status'],
          content[data]["squads"][0]["cards"][x]['priority']

        ];
        client.query(query, parameters, (err, res) => {

            console.log(err, res);

        })
      }
   }catch(e){
      console.log("undefined");

   }

client.end();

})();

OUTPUT

Error: Connection terminated at Connection. (C:\Users\TESTE\Documents\Autoportal\api\node_modules\pg\lib\client.js:254:9) at Object.onceWrapper (events.js:417:28) at Connection.emit (events.js:323:22)

2
  • 2
    You need await client.connect() and const res = await client.query() to handle the asynchronicity of the pg package. Otherwise client.end() gets called before you get your work done. Commented Mar 16, 2020 at 17:42
  • Got it, it seems like a silly mistake, could I just show a code snippet fixing this problem? I couldn't understand how to replicate this in my code, please! Commented Mar 16, 2020 at 17:49

1 Answer 1

2

You could try to use await client.connect()

and, for your queries, this

    res = await client.query(query, parameters);

in place of this

    client.query(query, parameters, (err, res) => {
        console.log(err, res);
    })
Sign up to request clarification or add additional context in comments.

2 Comments

You're welcome. I'm no genius, I've just had many pains in my neck getting this sort of thing to work.
I imagine, I'm a beginner in nodeJS, I come from python, where everything works easy, I'm suffering a lot rs'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.