I want to fetch some values from the current user Session and use them in MySQL query. I am working on Node.js and using redis to manage sessions.
File Name:User.js
var sessionUtils = require('./../services/sessionUtils');
var Constants = require('./../constants');
var config = require('./../config');
var databaseUtils = require('./../services/databaseUtils');
var redisUtils = require('./../services/redisUtils');
var util = require('util');
showUserPage: function* (next){
var queryString = "";
var query = "";
/*Do something to store session in variable*/
queryString = "select * from table where state='%s' and city='%s';";
query = util.format(queryString,/*state variable here*/, /*city variable
here*/);
var user = yield databaseUtils.executeQuery(query);
console.log(query);
yield this.render('user', {
user:user
});
}
File Name: sessionUtils.js
var redisUtils = require('./redisUtils');
var uuid = require('uuid');
var thunkify = require('thunkify');
saveUserInSession: function(user, cookies) {
var sessionId = uuid.v1(); // uuid: uniqe id every time
var sessionObj = {user: user};
redisUtils.setItemWithExpiry(sessionId, JSON.stringify(sessionObj), 86400); // 86400: for 1 day
cookies.set("SESSION_ID", sessionId);
},
getCurrentUser: thunkify(function(sessionId, callback) {
var currentUser;
if(sessionId) {
redisUtils.getItemWithCallback(sessionId, function(err, res) {
if(err) {
logger.logError(err);
}
if(res == null) {
callback(currentUser);
} else {
callback(err, JSON.parse(res).user);
}
});
} else {
callback(currentUser);
}
})
I am using line below in Login.js file to save user in session .
sessionUtils.saveUserInSession(results[0], this.cookies);
Help me out with this.
I have solved this problem by placing following code in place of /* Do something to store session in variable */
var sessionId = this.cookies.get("SESSION_ID");
var currentUser = yield sessionUtils.getCurrentUser(sessionId);
and used it in MySQL query as given below:
queryString = "select * from table where state='%s' and city='%s';";
query = util.format(queryString,currentUser.state, currentUser.city);
Hope, it helps others too.
Related
I have a server with 3 databases with identical tables.
DB1, DB2 and DB3.
When I work with a database I use:
app.js
var cnxDB= require('./routes/cnxDB');
app.post('/userSave', cnxDB.userSave);
cnxDB.js:
var sql = require('mssql');
var qs = require('querystring');
var colors = require('colors');
var config = {user: 'user',password: 'pass',server: '127.0.0.1',database: nameDB',
options: {
encrypt: false
}
};
sql.connect(config, function(err) {
//Connection
});
exports.userSave = function(req, res) {
//response
};
When initializing the application immediately makes the connection to the database.
I need to know how you can do to choose the database.
app.post('/selectBD', function(req, res){
var body = req.body; // accede a la informaciĆ³n enviada por el socket
console.log(body);
if(body.cnx == 1)
{
var cnx = require('./routes/bdUno');
app.get('/yuri', cnx.findall);
}
if(body.cnx == 2)
{
var cnx = require('./routes/bdDos');
app.get('/yuri', cnx.findall);
}
if(body.cnx == 3)
{
var cnx = require('./routes/bdTres');
app.get('/yuri', cnx.findall);
}
res.status(200).json("Ok");
});
Thank you.
In cnxDB.js set up 3 connections:
var connections = {
<dbname>: null,
<dbname>: null,
<dbname>: null
}
go to mssql and look at "Quick Example". It creates a connection and saves it in a variable. You'd want to do that 3 times for each db and save them in connections under the corresponding db name.
Then the functions you export from cnxDB.js should have a way to know which db you want them to use. By the looks of it you want to have some indication of what db needs to be used in the body of that request. You can use that to pick the db.
I have written an API that queries a MySQL database and outputs the corresponding results visiting an url. This is the code:
//server.js
var express = require('express'),
mysql = require('mysql'),
app = express(),
connectionpool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'password',
database : 'database'
});
app.get('/:transcript', function(req,res){
var var1 = req.param('transcript');
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
//Connection to MySQL
connectionpool.getConnection(function(err, connection) {
if (err) {res.send({result: 'error connection'})}
connection.query(query1, function(err, rows) {
if (err) {res.send({result: 'error query1'})};
counter = 0; root = {};
rows.forEach(function (row) {
build_actor(row.Transcript_alias, function(exprobject1) {
counter += 1;
//Defining and filling objects
main = {};
main.Official_transcript_name = row.Transcript_name;
main.Expression = exprobject1;
root[row.Transcript_alias] = main;
if (counter == rows.length) {
res.write(JSON.stringify(root, null, '\t'));
res.end();
}
});
});
connection.release();
});
//CallBack
function build_actor(transcript, callback) {
//Other, secondary queries:
var query2 = 'SELECT * FROM expression WHERE transcript_alias = "' + transcript + '";',
connection.query(query2, function(err, rows1) {
if (err) {res.send({result: 'error query2'})}
var exprobject2 = {},
exprobject1 = {};
for (i = 0; i < rows1.length; i++) {
Conditions = rows1[i].conditions;
Tissue = rows1[i].tissue;
FPKM = rows1[i].FPKM;
exprobject2[Tissue] = FPKM;
if (Conditions in exprobject1) {
exprobject1[Conditions].push(exprobject2);
} else {
exprobject1[Conditions] = [];
exprobject1[Conditions].push(exprobject2);
}
}
callback(exprobject1);
});
}
});
});
app.listen(3000);
console.log('Listening on port 3000');
This script calls a required file where there are my queries:
//queries.js
var server = require('./server'),
query1 = 'SELECT distinct(transcript_alias)\
FROM transcript_features \
WHERE f.transcript_alias = "' + var1 + '";';
exports.query1 = query1;
I go to the contents of this script this way:
http://localhost:3000/AC149829.2_FGT004
http://localhost:3000/AC148152.3_FGT007
When I first visit http://localhost:3000/AC149829.2_FGT004, the API shows the correct results for the variable AC149829.2_FGT004. However, when changing the variable to AC148152.3_FGT007, it continues showing the information for the variable AC149829.2_FGT004. In order to see the results for AC148152.3_FGT007, I must kill the script, call it again, and visit for the first time http://localhost:3000/AC148152.3_FGT007. In conclusion, results are not refreshed.
How is that? I tried with a simple:
app.get('/:transcript', function(req,res){
var input = req.param('transcript');
res.send(input);
});
but it works well...
EDIT. I found the source of my problem. query1 is always the same. The script only calls once:
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
There's a way to overcome this limitation?
I found the solution for my problem. As
//server.js
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
is executed once and remains in the cache, I changed my code without exporting var1:
//server.js
var queries = require('./queries'),
query1 = queries.query1 + var1;
and
//queries.js
var server = require('./server'),
query1 = 'SELECT distinct(transcript_alias)\
FROM transcript_features \
WHERE f.transcript_alias = ';
exports.query1 = query1;
In other words, I import my query to server.js without any variable. The variable is assigned at server.js.
I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:
function getBook(){
var tx = db.transaction("book", "readonly");
var store = tx.objectStore("book");
var index = store.index("by_getid");
var request = index.get("<?php echo $_GET['book'] ?>");
request.onsuccess = function() {
var matching = request.result;
if (matching !== undefined) {
document.getElementById("text-container").innerHTML = matching.text;
} else {
alert('no match');
report(null);
}
};
}
Solved Version:
function getBook(){
var db;
var request = indexedDB.open("library", 1);
request.onsuccess = function (evt) {
db = request.result;
var transaction = db.transaction(["book"]);
var objectStore = transaction.objectStore("book");
var requesttrans = objectStore.get(<?php echo $_GET['book'] ?>);
requesttrans.onerror = function(event) {
};
requesttrans.onsuccess = function(event) {
alert(requesttrans.result.text);
};
};
}
The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.
Try instead to create the db connection right inside the function. Do NOT use a global db variable.
index.get yields primary key. You have to get record value using the resulting primary key.
I has problem with transaction, it's return error db.transaction is not a function or return undefined.
You will try like this, it's working for me:
const table = transaction.objectStore('list');
const query = table.getAll();
query.onsuccess = () => {
const list = query?.result;
console.log(list);
};
I have 3 node js files :
mysqlconnection.js to store the database connection properties:
var mysql = require('mysql');
var cjson = require('cjson');
var yaml_config = require('node-yaml-config');
// project files
var config = yaml_config.load(__dirname + '/billingv2.yaml');
exports.execute = function(callback){
var connection = mysql.createConnection(
{
host : config.host,
user : config.user,
password : config.password,
database : config.database,
}
);
connection.connect();
return callback(null,connection);
}
subscriptionRestService.js to handle the REST api calls:
var express = require('express');
var app = express();
app.use(express.bodyParser());
var fs = require('fs');
// Project files
var mysql = require('./mysqlRestService.js');
// Get Resource Subscription data by Resourceuri
app.post('/pricingdetails', function(req, res) {
var workload = req.body;
if(workload.elements && workload.elements.length > 0)
{
var arr = [];
for(var index in workload.elements)
{
arr[index] = workload.elements[index].uri;
}
var resourceIdentifiers = arr.join(',');
}
console.log(resourceIdentifiers);
mysql.getPricingDetail(function(resourceIdentifiers,callback){
});
});
mysqlRestService.js to handle mysql queries/stored procedures:
// packages
var mysql = require('mysql');
var cjson = require('cjson');
var fs = require('fs');
var yaml_config = require('node-yaml-config');
// project files
var dbconnection = require('./mysqlconnection');
exports.getPricingDetail = function (resourceIdentifiers,callback){
console.log('entered into mysql function');
console.log(resourceIdentifiers);
var pricingDetail = {};
dbconnection.execute(function(err,response){
if(err){
throw err;
}
else
{
var selectqueryString = "call SP_ExposePricingDetailforUI('" + resourceIdentifiers + "')";
response.query(selectqueryString, function(err,pricingDetail){
if(err) {
throw err;
}
else
{
console.log(pricingDetail);
pricingDetail = pricingDetail;
}
});
}
});
//console.log('printing pricing details');
//console.log(pricingDetail);
};
problems faced
Unable to send the variable resourceIdentifiers from subscriptionRestService to mysqlRestService.js
Unable to return the pricingdetail from mysqlRestService.js to calling function in subscriptionRestService.
Any guidance greatly appreciated.
Unable to send the variable resourceIdentifiers from subscriptionRestService to mysqlRestService.js
Well, you didn't send it. It currently is a parameter of your callback function in the invocation, not an argument for the parameter of getPricingDetails. Use
mysql.getPricingDetail(resourceIdentifiers, function callback(result){
// use result here
});
Unable to return the pricingdetail from mysqlRestService.js to calling function in subscriptionRestService.
I've got no idea what pricingDetail = pricingDetail; was supposed to do. You have to call (invoke) back the callback here! Use
callback(pricingDetail);
I'm writing a Node.js application using Express and a PostgreSQL database using node-postgres. I want to look up the current user's username and real name based on their email, and set them in req.session. However, if I set them where I am in the code below, they are undefined when we leave that block (i.e. the first console.log statements print the correct info, the second set prints undefined. How can I solve this?
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
console.log(req.session.realname);
console.log(req.session.username);
});
console.log(req.session.realname);
console.log(req.session.username);
query.on('end', function() {
client.end();
});
The second pair of console.log will execute before the query-results are available (in the row event handler).
If your code is going to be used in an Express route, you would use something like this:
app.get('/', function(req, res) {
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
});
query.on('end', function() {
client.end();
res.send(...); // <-- end the request by sending back a response
});
});
An alternative for using the EventEmitter interface for node-postgres would be to just pass a callback to query (which looks better with Express IMHO):
client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email],
function(err, results) {
if (err)
// handle error
else
if (results.length)
{
req.session.realname = results[0].realname;
req.session.username = results[0].username;
}
res.send(...); // done
});