Timezone Issue In Sequelize Nodejs - javascript

I want Sequelize to use my local time for reading and writing to database.
in Sequelize config file I added timezone: "+04:30", but it is just for writing in database.
for writing in database when i add
dialectOptions: {
useUTC: false, // -->Add this line. for reading from database
},
i get this error :
Ignoring invalid configuration option passed to Connection: useUTC. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection
full config file :
const Sequelize = require("sequelize");
const sequelize = new Sequelize("db", "root", "", {
dialect: "mysql",
port: process.env.SQL_PORT,
host: "localhost",
charset: "utf8",
collate: "utf8_persian_ci",
logging: false,
dialectOptions: {
useUTC: false, // -->Add this line. for reading from database
},
timezone: "+04:30",
});

Finally I fixed it by getter in my model:
createdAt: {
type: Sequelize.DATE,
defaultValue: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
get: function () {
var isoDateString = new Date(this.getDataValue("createdAt"));
return new Date(
isoDateString.getTime() -
isoDateString.getTimezoneOffset() * 60 * 1000
);
},
},
and change my config file to :
const Sequelize = require("sequelize");
const sequelize = new Sequelize("db", "root", "", {
dialect: "mysql",
port: process.env.SQL_PORT,
host: "localhost",
charset: "utf8",
collate: "utf8_persian_ci",
logging: false,
timezone: "+04:30",
});

Related

How to save winston log file into mysql database?

I've configured the winston logger like this :
import winston from "winston";
const { SqlTransport } = require("winston-sql-transport");
const transportConfig = {
client: "mysql2",
connection: {
host: "localhost",
user: "root",
password: "Mahdi54321",
database: "todos",
// port: "3307",
},
tableName: "logs",
};
const alignColorsAndTime = winston.format.combine(
winston.format.colorize({
all: true,
}),
winston.format.label({
label: "[LOGGER]",
}),
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.printf(
(info) => `${info.label} ${info.timestamp} ${info.level} : ${info.message}`
)
);
export const logger = winston.createLogger({
level: "debug",
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
alignColorsAndTime
),
}),
new winston.transports.File({
filename: "logs/example.log",
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.json()
),
}),
new SqlTransport(transportConfig),
],
});
It only saves the first log and the next one is only saved in the file and not the database .
I'm guessing the new SqlTransport(transportConfig), doesn't run everytime so it can save every log to database .
How can I save every log one after another into mysql database ?
The package you use is deprecated, instead, you can use the winston-mysql package: https://www.npmjs.com/package/winston-mysql
implementation example as per documentation:
const options_default = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_default'
};
//custom log table fields
const options_custom = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_custom',
fields: {level: 'mylevel', meta: 'metadata', message: 'source', timestamp: 'addDate'}
};
//meta json log table fields
const options_json = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_json'
};
const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
}),
// or use: options_custom / options_json
new winstonMysql(options_default),
],
});
const rnd = Math.floor(Math.random() * 1000);
const msg = `test message ${rnd}`;
logger.debug(msg, {message: msg, type: 'demo'});
logger.error(msg, {message: msg, type: 'demo'});
logger.info(msg, {message: msg, type: 'demo'});
logger.warn(msg, {message: msg, type: 'demo'});

Heroku with Strapi, Application is not using production database

I've deployed my app to Heroku. It gives an Application Error message upon visit.
The logs gave me this:
[2021-02-15T01:04:05.882Z] debug ⛔️ Server wasn't able to start properly.
[2021-02-15T01:04:05.883Z] error Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
Which according to my guess, is that its trying to use local database. I think the app is not using the database.js located in config/env/production. The application runs fine with heroku local.
Below is the database.js I set for production env:
const parse = require("pg-connection-string").parse;
const config = parse(process.env.DATABASE_URL);
module.exports = ({ env }) => ({
defaultConnection: "default",
connections: {
default: {
connector: "bookshelf",
settings: {
client: "postgres",
host: config.host,
port: config.port,
database: config.database,
username: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
options: {
ssl: true,
},
},
},
});
Creating and printing the config var on heroku console results in expected values.
For some reason the deployment method in the strapi docs to heroku does not seem to work when you initially have set up your local database as Postgres.
I had the same problem as you and I fixed it using the NODE_ENV env variable.
Instead of creating a new production database config file in ./config/production/database.js you can simply extend the config file in ./config/database.js with the prod config and decide based on what NODE_ENV is set which one to return.
As example:
module.exports = ({ env }) => {
const parse = require("pg-connection-string").parse;
const config = parse(env("DATABASE_URL", "127.0.0.1"));
const devConfig = {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "127.0.0.1"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "db_name"),
user: env("DATABASE_USERNAME", "root"),
password: env("LOCAL_DB_PASSWORD"),
ssl: env.bool("DATABASE_SSL", false),
},
};
const prodConfig = {
client: "postgres",
connection: {
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
debug: false,
};
return
env("NODE_ENV", "development") === "production" ? prodConfig : devConfig
};

How to solve the database connection error [SequelizeConnectionError]? [duplicate]

I am trying to connect to a PostgreSQL Database that I've set up in Heroku.
const { Sequelize, DataTypes, Model } = require("sequelize");
// DB Configuration
const sequelize = new Sequelize({
database: "[won't show db]",
username: "[won't show username]",
password: "[won't show password]",
host: "ec2-54-221-195-148.compute-1.amazonaws.com",
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: true,
},
});
And this is what I am getting as the output:
SequelizeConnectionError: self signed certificate
This is due to an (accidental) breaking change in node-postgres version 8 (see this GitHub issue).
The solution is to pass rejectUnauthorized: false to the sequelize connection parameters inside of dialectOptions>ssl, as described here by GitHub user jsanta, bypassing the SSL certificate check (which is okay when connecting to a trusted server over a secure connection such as on your local host or between your own servers in the same network):
const sequelize = new Sequelize({
database: "xxxxx",
username: "xxxxx",
password: "xxxxx",
host: "xxxxx",
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false // <<<<<<< YOU NEED THIS
}
},
});
in my case none of the above works, I use the connection string method to apply pg configurations, so I set the query param sslmode=no-verify and I got it works
example
postgres://myuser:mypassword#myhost:5432/mydatabasename?sslmode=no-verify
It works for me (on sequelize config.json file):
"dialect": "postgres",
"dialectOptions": {
"ssl": {
"require": true,
"rejectUnauthorized": false
}
}
This works for me, in the config.json file
"development": {
"username": "dummy",
"password": "dummy",
"database": "dummy",
"host": "dummy",
"dialect": "postgres",
"dialectOptions":{
"ssl": {
"require": true,
"rejectUnauthorized": false
}
}
}
add the following in your code...
dbRDS=false

SequelizeConnectionError: self signed certificate

I am trying to connect to a PostgreSQL Database that I've set up in Heroku.
const { Sequelize, DataTypes, Model } = require("sequelize");
// DB Configuration
const sequelize = new Sequelize({
database: "[won't show db]",
username: "[won't show username]",
password: "[won't show password]",
host: "ec2-54-221-195-148.compute-1.amazonaws.com",
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: true,
},
});
And this is what I am getting as the output:
SequelizeConnectionError: self signed certificate
This is due to an (accidental) breaking change in node-postgres version 8 (see this GitHub issue).
The solution is to pass rejectUnauthorized: false to the sequelize connection parameters inside of dialectOptions>ssl, as described here by GitHub user jsanta, bypassing the SSL certificate check (which is okay when connecting to a trusted server over a secure connection such as on your local host or between your own servers in the same network):
const sequelize = new Sequelize({
database: "xxxxx",
username: "xxxxx",
password: "xxxxx",
host: "xxxxx",
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false // <<<<<<< YOU NEED THIS
}
},
});
in my case none of the above works, I use the connection string method to apply pg configurations, so I set the query param sslmode=no-verify and I got it works
example
postgres://myuser:mypassword#myhost:5432/mydatabasename?sslmode=no-verify
It works for me (on sequelize config.json file):
"dialect": "postgres",
"dialectOptions": {
"ssl": {
"require": true,
"rejectUnauthorized": false
}
}
This works for me, in the config.json file
"development": {
"username": "dummy",
"password": "dummy",
"database": "dummy",
"host": "dummy",
"dialect": "postgres",
"dialectOptions":{
"ssl": {
"require": true,
"rejectUnauthorized": false
}
}
}
add the following in your code...
dbRDS=false

Too many connection error in mysql - Nodejs & Mysql?

I am using nodejs-v9.2.0 and mysql in my application.
Error:
code: 'ER_CON_COUNT_ERROR'
errno: 1040
NPM Modules:
Mysql
Mysql wrapper
Code:
var mysql = require('mysql');
var pool = mysql.createPool({
canRetry: true,
database: "dbname",
host: "host",
user: "user",
password: "password",
connectionLimit: 100,
supportBigNumbers: true,
bigNumberStrings: true,
charset: 'utf8mb4_unicode_ci',
multipleStatements: true,
debug: true
waitForConnections: true,
queueLimit: 0
});
pool.on('connection', (connection) => {
connection.on('error', (err) => {
connection.release();
});
connection.on('close', (err) => {
console.error(new Date(), 'MySQL close', err);
});
});
var createMySQLWrap = require('mysql-wrap');
var sql = createMySQLWrap(pool);
Note:
I have noticed an open issue in the mysql npm github.
Any work around to solve this issue?
Any suggestion will be grateful

Categories

Resources