Reputation: 771
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)
Upvotes: 0
Views: 516
Reputation: 108641
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);
})
Upvotes: 2