Pool getConnection undefined - node.js

The problem is when I tried the pool connection via variable I'm getting following error
TypeError: sourCon.sourceDBConnection.getConnection is not a function
but if I try the normal connection it's fine.
The code is as follows:
File. ./db/source_db.js
module.exports =
{
sourceDBConnection: function () {
return mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'testdb'
});
}
};
File: app.js
app.get('/report-url', function (req, res) {
corporateModel.DetailReport(dateTime(),request);
})
File. ./models/corporate.js
var sourCon = require("../common_config/source_db");
module.exports =
{
DetailReport: function (dateTime,request,Q) {
var whereTripQueryAppend = "";
sourCon.sourceDBConnection.getConnection(function(err, finConnection) {
/* Get the last inserted ID */
finConnection.query("SELECT student_id FROM studen LIMIT 1", function (error, lastResults, fields) {
/* some process here */
})
})
})
}
Do you know why it works for the normal connection and it's not working for the pool connections? Also if I defined the connection in the same file it works fine. AS
File. ./models/corporate.js
var sourceDBConnection = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'testdb'
});
var sourCon = require("../common_config/source_db");
module.exports =
{
DetailReport: function (dateTime,request,Q) {
var whereTripQueryAppend = "";
sourceDBConnection.getConnection(function(err, finConnection) {
/* Get the last inserted ID */
finConnection.query("SELECT student_id FROM studen LIMIT 1", function (error, lastResults, fields) {
/* some process here */
})
})
})
}

Related

NodeJS Redis (ioredis) hgetall throwing undefined error

I am building a NodeJS app that connects to a Redis cluster using the ioredis module.
Overview of the issue:
A lookup query for a key that doesn't exist in the cache returns an empty object as expected
A lookup query for a key that DOES exist cache is throwing an error but the error is undefined.
I created a controller to create and manage the connection:
const redis = require('ioredis');
const consoleLogger = require('../logger/logger.js').console;
const redisCtrl = {};
redisCtrl.defaultPrefix = 'lookup:';
// Local variable to store the full time connection to Redis for lookups
let _redisClient;
// Redis connection config
redisCtrl.redisConnect = {
port: process.env.REDIS_PORT || 6379,
host: process.env.REDIS_HOST,
password: process.env.REDIS_PASSWORD
};
// Redis config
redisCtrl.redisConfig = {
dnsLookup: (address, callback) => callback(null, address),
redisOptions: {
tls: process.env.REDIS_SSL === 'false' ? false : true,
password: process.env.REDIS_PASSWORD,
maxRetriesPerRequest: 1
}
};
// Retrieve the redis connection
redisCtrl.redisClient = async () => {
if (!_redisClient) {
_redisClient = await redisCtrl.getNewConnect();
}
return _redisClient;
}
redisCtrl.getNewConnect = async () => {
let makeConnection;
if (process.env.REDIS_CLUSTER === 'true') {
makeConnection = new redis.Cluster([redisCtrl.redisConnect], redisCtrl.redisConfig);
} else {
makeConnection = new redis(redisCtrl.redisConnect);
}
makeConnection.on("connect", function (err) {
if (!err) {
consoleLogger.info("REDIS connected");
} else {
consoleLogger.info("REDIS connection error");
consoleLogger.error(JSON.stringify(err));
}
});
makeConnection.on("error", function (error) {
consoleLogger.info("REDIS error");
consoleLogger.error(JSON.stringify(error));
throw new Error(error);
});
return makeConnection;
}
redisCtrl.closeInstance = (cb) => {
if (_redisClient) {
_redisClient.quit(cb);
}
}
module.exports = redisCtrl;
This works to establish the connection.
However, when attempting to get a result, an empty error is thrown from the hgetall method.
/**
* Lookup asset by assetId in Redis cache
* Return asset data object
* #param {str} assetId
*/
assetsCtrl.lookupByAssetId = async (assetId) => {
// Prepend default cache prefix to lookup value
const lookupKey = `${redisPrefix || `lookup:`}${assetId}`;
let cachedAsset;
try {
cachedAsset = await assetsCtrl.redisClient.hgetall(lookupKey);
} catch (e) {
consoleLogger.error(`Lookup by assetId failed. Lookup key: ${lookupKey}`);
consoleLogger.error(e);
throw new Error(e);
}
return cachedAsset;
}
The error is thrown but the error is undefined. The "catch" block of the redisClient.hgetall(lookupKey) line is getting called but the error is not defined.
error: Lookup by assetId failed. Lookup key: lookup:test123456789
**error: undefined {"command":{"name":"hget","args":["lookup:test123456789"]}}**
Questions: How can I troubleshoot this issue? How can I see the details of the error that is being thrown?
As stated in the comments above, the hgetall() is not working because the datatype corresponding to the lookup value was not hash.
Changing it to get() has fixed the issue.

How to migrate from Mamp DB to Cloudant DB in Node.js application

I am new in Cloudant db. I need to migrate from Mamp db to Cloudant. I am getting form data and inserting it to DB but with Cloudant I am not able to understand insert command as it work differently (Object base save). How can I make a Db connection?
The insert code is given below:
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { promisify } = require ('util');
// const db = mysql.createConnection({
// host: process.env.DATABASE_HOST,
// port: process.env.DATABASE_PORT,
// user: process.env.DATABASE_USER,
// password: process.env.DATABSE_PASSWORD,
// database: process.env.DATABASE
// });
Cloudant = require('#cloudant/cloudant');
cloudAntConfig = {
url: process.env.CLOUD_ANT_URL,
apiKey: {iamauth: {iamApiKey: process.env.CLOUD_ANT_APIKEY}},
database: process.env.CLOUD_ANT_DB
};
exports.assessment = (req,res) => {
console.log(req.body);
// console.log(user.User_ID );
const { TeamName, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10, question11, question12, question13, question14, question15, question16, question17, question18, question19, question20, question21, question22, question23, question24, question25, question26, question27, question28, question29, question30, question31, question32, question33, question34, question35 } = req.body;
// console.log(parseInt(question3)+parseInt(question4));
// some code about data goes here
db.query('INSERT INTO assessment_result SET ?',{User_Id : 1,Team_Name : TeamName, Dimension_1_Score : (dime_1_total/25)*100, Dimension_2_Score : (dime_2_total/50)*100, Dimension_3_Score : (dime_3_total/50)*100, Dimension_4_Score : (dime_4_total/50)*100, Total_Score : final_total, Total_Score_Persentage : (final_total/175)*100 },(error,results)=>{
// res.render('register');
})
}
The Getting Started section of the #cloudant/cloudant README shows how to insert a document into a Cloudant database.
const Cloudant = require('#cloudant/cloudant');
cloudAntConfig = {
url: process.env.CLOUD_ANT_URL,
plugins: { iamauth: { iamApiKey: process.env.CLOUD_ANT_APIKEY } }
}
const cloudant = Cloudant(cloudAntConfig);
const db = cloudant.use(process.env.CLOUD_ANT_DB)
// ...
db.insert({User_Id: 1, /* etc the rest of your document content */}, (err, data) => {})
Probably worth noting though that #cloudant/cloudant is deprecated and if you are writing new code you should consider using #ibm-cloud/cloudant.

I'm having trouble sending a post request in nodeExpress

i really don't know what it could be a problem but everytime i try to post i get a log error : ER_BAD_NULL_ERROR: Column 'idmedecin' cannot be null
i've seen allot of similar questions (trouble in post req) but nothing solved my problem and i cannot see what im doing wrong since idmedcin is clearly not NULL
reqLink used = http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pim',
multipleStatements: true
});
mysqlConnection.connect((err) => {
if (!err)
console.log('DB connection succeded.');
else
console.log('DB connection failed \n Error : ' + JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is runnig at port no : 3000'));
app.post('/rendezvousinsert/',(req,res)=> {
var post= {
idmedecin : req.body.idmedecin ,
idpatient : req.body.idpatient ,
date : req.body.date ,
etat : req.body.etat
};
mysqlConnection.query('INSERT INTO rendezvous SET ?' , post, function(error) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
});
here is my table structure
You're sending data through query string http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1 but trying to access it through req.body
idmedecin=1&idpatient=1&date=546654&etat=1 This data is available as
req.query.idmedecin // 1
req.query.idpatient // 1
req.query.date // 546654
// etc
You are trying to get the fields from the request body, but in your example you send them as query params.
I think the correct way is to send the object inside the POST body and not as query params, but if you want the request to remain as in your example, it should look like this:
var post= {
idmedecin : req.query.idmedecin ,
idpatient : req.query.idpatient ,
date : req.query.date ,
etat : req.query.etat
};

Return the specific contents from a field of data in the result-set of a select query

I have select query that pulls a row of a data from a largeObject stored in a PostgreSQL table. The particular piece of data in the field is a html file.
I can output the name of the field of data into the console which appears as 16543 (for 16543kB).
So, my burning question is how I can return the actual contents (html) so that I can subsequently export it as one object and send it to the browser.
I am using node and express heres my source code so far:
var database = require('../database/postgresDB.js');
var pg = require('pg');
var html = {};
var connectionString = "postgres://dabladmin:dabldem#localhost:5432/dablpatient";
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('SELECT * FROM htmlfiles WHERE id = 1', function(err, result){
console.log(JSON.stringify(result));
console.log(result.rows[0].htmlfile);
html = result.rows[0].htmlfile;
//return result.rows[0].htmlfile;
//console.dir(html);
});
module.exports = html;
This cannot be done directly. You need to export a function which will return the promise.
Following is an idea of how it can be done. Note: The code is not tested.
// htmlfile.model.js
const promise = require('bluebird'); // or any other Promise/A+ compatible library;
const initOptions = {
promiseLib: promise // overriding the default (ES6 Promise);
};
const pgp = require('pg-promise')(initOptions);
// Database connection details;
const cn = {
host: 'localhost', // 'localhost' is the default;
port: 5432, // 5432 is the default;
database: 'myDatabase',
user: 'myUser',
password: 'myPassword'
};
const db = pgp(cn); // database instance;
const getHtml = id => db.oneOrNone('SELECT * FROM htmlfiles WHERE id = $1', id);
module.exports = getHtml;
Inside some.controller.js:
const html_model = require('./htmlfile.model.js');
html_model.getHtml(1)
.then(data => {
if(data) {
// record found
res.send(data.htmlfile);
} else {
// record not found, do something else
}
})
.catch(error => {
// an error occurred
});

Multiple database connection in single connection pool using Node JS

I am trying to create a database connection pool in Node js using generic-pool package. With single database the pool is working fine but I want to use more than one database in single pool to be use. In this context I am facing issue. Generic pool is not creating pool for both the database in single pool. Below is my code. I am using trireme-jdbc for JDBC connection ang generic-pool for connection pooling.
var Pool = require('C:JCI/trireme-jdbc/node_modules/generic-pool').Pool;
var jdbc = require('C:/Program Files/nodejs/node_modules/trireme-jdbc');
var configOpenedge = require('C:/Program Files/nodejs/node_modules/trireme-jdbc/testconf/config-openedge.js');
var configPostgre = require('C:/Program Files/nodejs/node_modules/trireme-jdbc/testconf/config-postgre.js');
var pool = new Pool({
name : 'Anil-JCI',
create : function(callback) {
var connOpenedge = new jdbc.Database({
url : configOpenedge.url,
properties : configOpenedge.properties,
});
var connPostgre = new jdbc.Database({
url : configPostgre.url,
properties : configPostgre.properties,
/*
* minConnections : 1, maxConnections : 2000, idleTimeout : 60
*/
});
callback(null, connOpenedge);
},
destroy : function(client) {
client.end();
},
max : 10,
// optional. if you set this, make sure to drain() (see step 3)
min : 2,
// specifies how long a resource can stay idle in pool before being removed
idleTimeoutMillis : 30,
// if true, logs via console.log - can also be a function
log : true
});
console.log("connection created");
pool.acquire(function(err, clientOpenedge, clientPostgre) {
if (err) {
throw err;
}
else {
clientOpenedge.execute(
'select * from "po" where "po-num" = ? and "vend-num" = ? ', [
4322452, 4301170 ], function(err, result, rows) {
// pool.release(client);
console.log(err);
rows.forEach(function(row) {
console.log(row);
});
console.log("Openedge Data Printed...");
});
clientPostgre.execute("select * from employees ",
[ ], function(err, result) {
// pool.release(client);
console.log("we are in postgre");
console.log(result);
console.log("Postgre Data Printed...");
});
}
});

Resources