Conditionally Assign const value in js - javascript

I'm trying to assign a different value to sequelize based on whether the app is running locally or on the server. This is my code:
const sequelize = production
? sequelizeHeroku.connect(Sequelize)
: new Sequelize(database, user, password, {
host,
dialect: "mysql",
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
This doesn't work locally, as when I log the value of sequelize it is false. However, if I try to assign the variable like this:
const sequelize = new Sequelize(database, user, password, {
host,
dialect: "mysql",
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
it works just fine. I also checked that console.log(production == true) prints out false. What am I doing wrong?

It's better to use NODE_ENV environment variable. E.g.
index.ts:
import { Sequelize } from 'sequelize';
import assert from 'assert';
const database = 'sample';
const user = 'testuser';
const password = 'testpass';
const host = '127.0.0.1';
const sequelize =
process.env.NODE_ENV === 'production'
? 'sequelize heroku'
: new Sequelize(database, user, password, {
host,
dialect: 'mysql',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000,
},
});
assert(process.env.NODE_ENV === 'production', 'NODE_ENV should be "production"');
assert(sequelize === 'sequelize heroku', 'Should use heroku sequelize in production environment');
Execute code in production environment:
NODE_ENV=production npx ts-node ./index.ts
No assertion failed. It works as expected.

Related

NESTJS AWS Lambda & Sequelize connection pool

Since I have given the pool parameters as mentioned in the below code snippet, Is necessary to close the connection after each lambda invocation?
This aws lambda function is supposed to be triggered every minute, is the pool parameter only enough to close the connection?
export const databaseProviders = [
{
provide: 'vendorDB',
useFactory: async (awsSecrets: AwsSecretsService) => {
const { host, port, username, password, database } =
await awsSecrets.getVendorDbConfig();
const sequelize = new Sequelize({
dialect: 'postgres',
host,
port,
username,
password,
database,
logging: true,
pool: {
max: 1,
min: 0,
idle: 1000,
},
});
sequelize.addModels([VendorEntity]);
// await sequelize.sync();
return sequelize;
},
inject: [AwsSecretsService],
},

knex broken after upgrading from Node.js v12 to Node.js v16.4.0

I'm experiencing below error after upgrading to Node.js v16.4.0 (from Node.js v12).
I'm using knex to connect to db (postgres) and using ORM - objection.js.
KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
Please help to resolve!
import Knex from "knex";
const getConnection = () => {
try {
return Knex({
client: 'pg',
connection: {
user: 'user',
password: 'password',
host: 'dbhost',
port: 5432,
database: 'dbname',
},
pool: {
min: 0,
max: 10,
idleTimeoutMillis: 10000,
acquireTimeoutMillis: 30000,
},
acquireConnectionTimeout: 2000,
});
}
catch (err) {
throw err;
}
}
const getTransaction = () => {
const con = getConnection();
const trx = con.transaction();
return trx;
}
Having had the same issue, I traced the problem to an old version of the "pg" package.
Doing
npm i pg#latest
fixed it

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
};

Connection Pooling in Nodejs (Using sequelize)

I write the code below. According to my understanding the "max:" in pool shows the max number of connection we can create in pool. So if I set the value of max as 0. Then it should not established any connection. I just want to clarify this.
var sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD, {
pool:{
max: 0,
min: 0,
idle: 10000,
acquire:30000
},
logging: console.log("connection created"),
host: process.env.DATABASE_HOST,
dialect: 'mysql',
operatorsAliases: false
}
);
I have no idea about Sequelize but simply we can create a connection this way.I think this will be little bit helpful for you.
/**
* create connection pool
*/
var con = mysql.createPool({
connectionLimit: 100000,
host: 'enter host',
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME
});
con.getConnection(async function(err, connection) {
let result=connection.query('SELECT * FROM table_name');
console.log(result);
if(err) throw err;
})
what's wrong with the way they have it set up in their examples exactly?
const sequelize = new Sequelize(config.db.uri, {
pool: {
max: 100,
min: 0,
idle: 10000,
},
dialectOptions: {
ssl: config.db.ssl,
},
// logging: logger.debug.bind(logger),
});
the models utilize it on their own... what am i missing here?
For "sequelize": "^5.21.3", you can't set pool.max to 0 anymore. If you do this, sequelize will throw an error:
max must be an integer > 0

How to export database connection string node / node.js

I am trying to turn the following database connection string into a module:
require('dotenv').load();
var knex = require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: process.env.DB_USER,
password: process.env.DB_USER_PASSWORD,
database: process.env.DB_NAME
},
pool: {
min: 0,
max: 7
}
});
So far I tried:
require('dotenv').load();
module.exports = {
knex : require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: process.env.DB_USER,
password: process.env.DB_USER_PASSWORD,
database: process.env.DB_NAME
},
pool: {
min: 0,
max: 7
}
})
}
In my app.js file:
var knex = require('./models/database');
knex.select().table('users').then(function(result) {
result.forEach(function(value) {
console.log(value.first_name);
});
});
This returns the error 'knex' is undefined. I think the way my module is being exported is incorrect... can someone help?
Thank you!
It's because you're exporting an object containing knex.
Either add knex to the require:
var knex = require('./models/database').knex;
or change your export to
module.exports = require('knex')({ ... })

Categories

Resources