Error with pg-connection-string and sequelize in a React application - node.js

I am trying to use the sequelize ORM with a React application. I've installed the sequelize and pg-connection-string packages, but I am getting an error when trying to connect to the database. The error message is:
ERROR in ./node_modules/pg-connection-string/index.js 4:9-22
Module not found: Error: Can't resolve 'fs'
I've tried uninstalling and reinstalling the packages, clearing the npm cache, and using a different version of the packages, but I am still getting the same error.
I am using the following versions:
React: 16.13.1
Sequelize: 6.3.5
pg-connection-string: 2.0.0
Here is my code:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('texteditor', 'root', '', {
host: 'localhost',
dialect: 'mysql'
});
const Database = sequelize.define('database', {
title: {
type: Sequelize.STRING
},
content: {
type: Sequelize.TEXT
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
sequelize.sync();
I would greatly appreciate any help or suggestions on how to resolve this issue.

So typically you do not connect to databases in the UI layer of an application. Likely the reason it can't retrieve the fs module is that you're running in a browser, where the sequelize package expects you to be using the node runtime. This is where you would build a backend server using Node.JS, which would connect to the DB and in turn respond to the UI with the information it needs.

Related

AWS Redis Cluster MOVED Error using redis node library

I have created a Redis MemoryDB cluster with 2 nodes in AWS:
I connect to it using redis node library v4.0.0 like this:
import { createCluster } from 'redis';
(async () => {
const REDIS_USERNAME = 'test-username';
const REDIS_PASSWORD = 'test-pass';
const cluster = createCluster({
rootNodes: [
{
url: `rediss://node1.amazonaws.com:6379`,
},
{
url: `rediss://node2.amazonaws.com:6379`,
},
],
defaults: {
url: `rediss://cluster.amazonaws.com:6379`,
username: REDIS_USERNAME,
password: REDIS_PASSWORD,
}
});
cluster.on('error', (err) => console.log('Redis Cluster Error', err));
await cluster.connect();
console.log('connected to cluster...');
await cluster.set('key', 'value');
const value = await cluster.get('key');
console.log('Value', value);
await cluster.disconnect();
})();
But sometimes I get the error ReplyError: MOVED 12539 rediss://node2.amazonaws.com:6379 and I cannot get the value from the key.
Do you have any idea if there is something wrong with the configuration of the cluster or with the code using redis node library?
Edit:
I tried it with ioredis library and it works, so it's something wrong with the redis library.
Node.js Version: 16
Redis Server Version: 6
I had created an issue to redis library, so it's going to be solved soon with this PR.

Sync Sequelize Databases on Serverless app

I am using sequelize with MySQL on the Serverless offline app.
I am not sure how to sync all models on serverless start?
I am tried to do this
import Sequelize from "sequelize";
import mysql2 from 'mysql2';
const sequelize = new Sequelize('database', 'root', '', {
dialect: 'mysql',
dialectModule: mysql2,
host: 'localhost',
});
const getSequelize = () => {
sequelize.sync({ force: false })
.then(() => {
console.log(`Database & tables synchronised!`)
});
return sequelize;
}
export default getSequelize();
This approach syncs models that are imported into controller, so the only way in this case to sync all models is to include all models in every controller.
This does not look like a good example.
Do you have any idea?
Use sequelize.sync only for development purposes. Use sequelize migrations for production.
There must be some way to run console command db:migrate in your environment. When you push all the migration code use that command to update your database to the last version.

Connection to postgresql db from node js

I'm tyring to make a connection from my nodejs script to my db connection, but seems like there is a suspicius issue i'm not able to figure out.
At the moment, this is my code:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: '192.168.1.xxx',
database: 'database',
password: 'password',
port: 5432,
});
pool.on('error', (err, client) => {
console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
.then((client) => {
client.query(query)
.then(res => {
for (let row of res.rows) {
console.log(row);
}
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
The issue seems to be in pool.connect(), but i can't understand what i'm missing because i got no errors in the log. I've installed pg module in the directory of my project with npm install --prefix pg and i know modules are loaded correctly.
I edited postgresql.conf:
# - Connection Settings -
listen_addresses = '*'
and pg_hba.conf
host database user 192.168.1.0/24 md5
to make the database reachable via lan and seems liek it works, because i'm able to connect successfully with apps like DBeaver...but i can't with NodeJS.
It's possible there is some kind of configuration i've to active?

Node-Postgres SequelizeConnectionError: password authentication failed for user

I am developping a backend application with node and sequelize. My database is from postgresql.
When lauching the app, the database connection works fine, but when it tries to communicate with the database to read or update, it fails with a connection error:
password authentication failed for user "wushin".
Seems really weird to me because database connection has already been done, and password has been validated. Do you guys know what's happening ? Maybe an issue with pg module but I tried different versions.
Versions
Node: 10.17.0
Sequelize: 5.21.3
Postgres: 10.11
pg module: 7.17.1
-> This code works fine:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
-> But this promise fails with SequelizeConnectionError:
models.Question.findAll()
.then(data => {
console.log('-> Succeeded data fetching\n')
console.log(data)
})
.catch(err => {
console.log('-> Failed data fetching\n')
console.log('Error', err)
})
Logs:
yarn run v1.19.2
$ node index.js
Example app listening on port 4000 or something!
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
- Trying to fetch data:
-> Failed data fetching
Error:
{ SequelizeConnectionError: password authentication failed for user "wushin"
at connection.connect.err (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24)
at Connection.connectingErrorHandler (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/connection.js:128:12)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'SequelizeConnectionError'
It seems that you pass no configurations to Sequelize but the host. The minimum configurations are host, port, databasename, dialect username, and password.
From the docs:
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately const sequelize = new
Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Passing a connection URI const sequelize = new
Sequelize('postgres://user:pass#example.com:5432/dbname');
I finally fixed this. The issue was that with sequelize, requiring the models calls an index.js that is supposed to do the sequelize connection for you, using the config repository sequelize creates.
My connection to sequelize was working well but the one that was launched by requiring models had some bad information on my database.
Therefore I could not use the imported model to fetch data on the database.
I inserted good config information :
require('dotenv').config()
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
},
test: {
url: process.env.DATABASE_TEST_URL,
dialect: 'postgres',
},
production: {
url: process.env.DATABASE_PROD_URL,
dialect: 'postgres',
},
}
And completely removed the line that I wrote myself:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
It is now the models/index.js that connects to the database with :
const sequelize = new Sequelize(process.env.DATABASE_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})

how to catch Sequelize connection error

How to catch a sequelize connection error in case there is one?
I tried to do
var connection = new Sequelize("db://uri");
connection.on("error", function() { /* perhaps reconnect here */ });
but apparently this is not supported.
I wanted to do this because I think sequelize might be throwing an occasional unhandled ETIMEOUT and crashing my node process.
Currently I am using sequelize to connect a mysql instance. I only need it for like 2-3 hours and during that time I will be doing a many read queries. The mysql server will not be connected to anything else during that time.
Using sync() for this is considerably dangerous when using external migrations or when database integrity is paramount (when isn't it!)
The more up-to-date way of doing this is to use authenticate()
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Using sequelize sync method provides an easy way to catch the error.
The then block handles a Successful connection and the catch handles the rejection.To get a detailed reason for a failure access the error object.
example: error.message e.t.c
Hope this helps.
sequelize.sync().
then(function() {
console.log('DB connection sucessful.');
}).catch(err=> console.log('error has occured'));
Use sequelize sync for that
var Sequelize = require('sequelize');
sequelize = new Sequelize(config.database, config.username, config.password, {
'host' : config.host,
'dialect' : config.dialect,
'port' : config.port,
'logging' : false
})
sequelize.sync().then(function(){
console.log('DB connection sucessful.');
}, function(err){
// catch error here
console.log(err);
});

Resources