node-postgres reconnect when connection failed [closed] - node.js

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my db connection code of nodejs project, in some situation my db is down (not working), i want to try reconnecting to db, but i don't know how to that, please help me
const { Client } = require('pg');
const postgis = new Client({
user: process.env.PGUSER,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
password: process.env.PGPASSWORD,
port: process.env.PGPORT
});
console.log(`Connecting to PostGIS database ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`);
postgis.connect()
.then(() => {
console.log(`PostGIS connected to: ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`)
})
.catch((e) => {
// console.error(`PostGIS connection error: ${e}`)
setTimeout(function () {
console.log("entering again")
postgis.connect();
}, 10000);
});
error:
(node:10299) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10299) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

You can handle it in catch block and reconnect to posgres
setTimeout(function () {
postgis.connect();
}, 10000);

Related

Mongoose query not running - "cursor.toArray is not a function"

MongoDB beginner, having trouble getting queries to work. Was following a tutorial of sorts and it was a demo notes app. Their syntax for saving new notes works fine.
However when it comes to printing out the list of notes, there seems to be something wrong in the syntax given to me or something im doing wrong.
const mongoose = require("mongoose");
const url =
"mongodb+srv://Saif:<password>#cluster0.8d2lb.mongodb.net/notes-app?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true,
});
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
});
const Note = mongoose.model("Note", noteSchema);
Note.find({}).then((result) => {
result.forEach((note) => {
console.log(note);
});
mongoose.connection.close();
});
After looking up documentation, the actual syntax of find is a little different where they pass in a callback instead of using promises. But changing that block to use a callback still doesnt work
Note.find({}, (error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
Error
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (D:\Folders\Documents\CS.........
(Use `node --trace-warnings ...` to show where the warning was created)
(node:27108) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27108) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.find method from model returns Query object not Cursor
For cursor you need to do .exec
Note.find({}).exec((error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})

Unit Testing HTTP Post request with database access

Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:
"use strict";
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const app = require('../../../app');
chai.request('http://localhost:8080')
.put('/tempValue')
.send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
.then(function (res) {
expect(res).to.have.status(200);
})
.catch(function (err) {
throw err;
});
I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using const dbPath = "./database/database.db"; and const dbConnection = sqlite.open(dbPath, { Promise });
I also seem to get errors about incorrect use of .catch? This is the error log:
(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Thanks for any help!
EDIT:
This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.
app.ws.use(route.all('/tempValue', function (ctx){
client.on('message', async function(topic,message){
console.log(topic, message.toString());
if (topic === '302CEM/Penguin/Room1/Temperature'){
const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
try {
const temptostring = message.toString();
const db = await dbConnection;
await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
ctx.websocket.send(temptostring);
} catch (err) {
console.log(err);
}
}
})
}));

`newSession` not found when using local capabilities

I'm facing this error when trying to use BrowserStack local capability:
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:67602) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
My code is pretty simple:
const webdriver = require('selenium-webdriver');
const browserstack = require('browserstack-local');
const runTestSuite = () => {
const capabilities = {
browserName: 'Chrome',
browser_version: '80.0 beta',
os: 'OS X',
os_version: 'Catalina',
resolution: '1024x768',
'browserstack.user': '<user>',
'browserstack.key': '<key>',
'browserstack.local': true,
'browserstack.localIdentifier': 'ardotest',
// 'browserstack.use_w3c': true,
acceptSslCerts: true,
name: 'Bstack-[Node] Sample Test-OS X Catalina-Chrome 80',
};
// https://www.browserstack.com/question/663
const driver = new webdriver.Builder()
.usingServer('http://localhost:3000') // tried using the IP that I got from Network settings on my machine, it spat out the same error
.withCapabilities(capabilities)
.build();
console.log('quit');
driver.quit();
};
// creates an instance of Local
const bsLocal = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const bsLocalArgs = { key: '<browserstack-accesskey>' };
// https://github.com/browserstack/browserstack-local-nodejs/blob/master/lib/Local.js
// starts the Local instance with the required arguments
bsLocal.start(bsLocalArgs, function(err) {
if (err) {
console.error(err);
return;
}
if (!bsLocal.isRunning()) {
return;
}
try {
runTestSuite();
} catch (e) {
console.error(e);
} finally {
// stop the Local instance
bsLocal.stop(function(err) {
if (err) {
console.error(err);
}
console.log('===== BrowserStack tunnel stopped =====');
});
}
});
Versions:
"selenium-webdriver": "^4.0.0-alpha.5",
"browserstack-local": "^1.4.5",
My local environment:
"node": "10.16.3",
"npm": "6.8.0",
macOS 10.14.6
Looking through the code, it's clear that it's trying to hit /session url to create a new session or something. I'm not sure whether I should support /session manually, or I'm just missing something that's really stupid here?
It seems that BrowserStack provides it's own Hub URL for the test executions. You may try changing the hub URL from localhost:3000 to BrowserStacks hub url.
Referring to this code -> .usingServer('http://localhost:3000')
This document has more details: https://www.browserstack.com/local-testing/automate
You just need to make sure to have the same localIdentifier arg in both capabilities AND bsLocalArgs.
That is, both in .withCapabilities(<here>) and new browserstack.Local().start(<here>, ...)

Chrome launcher exits with UnhandledPromiseRejectionWarning

I am trying to set up chrome-launcher to output all console messages to terminal. My code looks like this
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
(async function() {
async function launchChrome() {
return await chromeLauncher.launch({
chromeFlags: [
'--window-size=1200,800',
'--user-data-dir=/tmp/chrome-testing',
'--auto-open-devtools-for-tabs'
]
});
}
const chrome = await launchChrome();
const protocol = await CDP({
port: chrome.port
});
const {
DOM,
Network,
Page,
Runtime,
Console
} = protocol;
await Promise.all([Network.enable(), Page.enable(), DOM.enable(), Runtime.enable(), Console.enable()]).catch(console.log);
// REMARKS: messageAdded is fired every time a new console message is added
Console.messageAdded((result) => {
console.log(result);
});
})();
I copied some of this from the question here: How to get console.log output in Terminal via Headless Chrome Runtime.evaluate
When I try to navigate to a page, none of the console messages show up in the terminal, and the chrome-launcher exits with the following error:
(node:14531) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:64656
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1083:14)
(node:14531) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14531) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Can't connect Node.js to remote database MariaDB

I try to connect to my MariaDB database using Node.js based on this tutorial:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'myhost.com',
user:'root',
password: 'password',
database: 'db_p',
connectionLimit: 2
});
async function asyncFunction() {
let conn;
try {
console.log('establishing connection')
conn = await pool.getConnection();
console.log('established')
const rows = await conn.query("SHOW TABLES");
console.log(rows);
} catch (err) {
console.log(err)
throw err;
} finally {
if (conn) return conn.end();
}
}
but all I get is this error:
establishing connection
{ Error: retrieve connection from pool timeout
at Object.module.exports.createError (/Users/jan/Developer/microservice/node_modules/mariadb/lib/misc/errors.js:55:10)
at rejectTimeout (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:267:16)
at Timeout.rejectAndResetTimeout [as _onTimeout] (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:287:5)
at ontimeout (timers.js:486:15)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
fatal: false,
errno: 45028,
sqlState: 'HY000',
code: 'ER_GET_CONNECTION_TIMEOUT' }
(node:76515) UnhandledPromiseRejectionWarning: Error: retrieve connection from pool timeout
at Object.module.exports.createError (/Users/jan/Developer/microservice/node_modules/mariadb/lib/misc/errors.js:55:10)
at rejectTimeout (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:267:16)
at Timeout.rejectAndResetTimeout [as _onTimeout] (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:287:5)
at ontimeout (timers.js:486:15)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
(node:76515) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This errororiginated either by throwing inside of an async function without a catch block, or byrejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:76515) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I programmed in JS for last two years, but I'm new to Node.js and I thought it should work out of the box. Anyone?
The problem was that in phpMyAdmin I didn't added my home ip address so I can connect. For those who are just starting with it - you can create multiple users with the same name and password so you can actually have access from multiple IP's (like localhost, ::1 or 127.0.0.1 which is quite the same, but still required just for sure).
I have added additional user with same credentials pointing to my IP and it solved the problem.
For others with the same error message, particularly if the connection works the first few times but not after that, the error can happen if you don't end the connection with conn.end. Not OPs problem, but perhaps others.
For me the problem was solved by adding port: 3307 as another pool creation parameter.
Port 3306 seems to be default but some servers seem to prefer 3307.

Resources