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.
Related
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.
In the following code, data are retrieved from a database into JSON. What I would like to do is to display each single data as a plain text:
var http = require("http");
var mysql = require('mysql');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/Search.html', function (req, res) {
res.sendFile( __dirname + "/" + "Search.html" );
})
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'passpass',
database : 'SocialQuery',
}
);
connection.connect();
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
SearchType:req.body.SearchTypes,
Term:req.body.term
};
//var vas = JSON.stringify(response);
var search = req.body.SearchTypes;
var term = req.body.term;
var queryString;
if(search == 'Author')
{
queryString = 'Select Label,TDate from Tweet where AuthorID IN (select ID from Author where Lable = ?)';
}
else if(search == 'Mention')
{
queryString = 'select Tweet.Label, Tweet.TDate, Author.Lable from Tweet, Author where Tweet.ID IN (select TweetID from TweetMention where MentionID IN (select ID from Mention where Label = ?)) AND Author.ID = Tweet.AuthorID'
}
var query = connection.query(queryString, [term], function(err, rows) {
console.log(rows);
var tweet = JSON.stringify(rows);
res.write("Author: " + tweet.Lable);
res.write("Date: " + tweet.TDate);
res.end();
});
console.log(query.sql);
})
//}).listen(8081);
http.createServer(app).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
When I print the data using res.write(JSON.stringify(rows)); I got the following:
[{"Label":"lest play hero","TDate":"2016-03-12T00:00:00.000Z","Lable":"esti_jony"},{"Label":"u r the best ! Ill always keep","TDate":"2016-03-08T00:00:00.000Z","Lable":"adam03cooper03"}]
but when I run the code above, I got:
Author: undefined Date: undefined
What I understood is the problem because two rows of data have been retrieved and I do not know how to let it display each author (Lable) and each date (TDate).
You're converting a javascript object to a JSON string and then trying to access the javascript object's properties on the string. That won't work. You want to use the javascript object instead, but since there is more than one row, you will have to either choose which one you want to respond with or write all rows or whatever your use case calls for.
For example:
var query = connection.query(queryString, [term], function(err, rows) {
if (err) throw err;
for (var i = 0; i < rows.length; ++i) {
var tweet = rows[i];
res.write("\nAuthor: " + tweet.Lable);
res.write("\nDate: " + tweet.TDate);
if (i + 1 < rows.length)
res.write('\n');
}
res.end();
});
I'm using localhost and have all the modules set up correctly and I've checked that the database exists. When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database, but for some reason it isn't working.
var express = require('express');
var _ = require('underscore');
var mongoose = require('mongoose');
var podStore = require('./lib/pod-handler.js');
var podsLibrary = require('./lib/pods-library.js');
var podList = [];
var mongoPort = 27017;
var app = express();
var port = 3000;
var router = express.Router();
var pods = podsLibrary.list();
mongoose.connect('mongodb://localhost:'+mongoPort+'/pods');
router.route('/').get(function(request, response) {
//console.log('You hit an empty URL .. :(');
response.status(503).send("Service Unavailable");
});
router.route('/lib').get(function(request, response) {
//console.log('You hit an empty URL .. :(');
response.status(200).send("Cool beans!");
});
router.route('/pods/list').get(function(request, response){
if(!pods){
return response.status(503).send("Service Unavailable");
}
return response.status(200).send(makeReadableList(pods));
function makeReadableList(pods){
var podsHtml = " ";
_.each(pods, function(value, key){podsHtml = podsHtml + key});
return podsHtml;
}
});
router.route('/pods/add').post(function(request, response){
if (!request.query){
return response.status(400).send("Please give first name");
}
var payload = request.query;
if (!payload.firstName){
return response.status(400).send("give name");
}
podStore.save({
firstName: payload.firstName,
lastName: payload.lastName
}, function(){
return response.status(200).send(payload.firstName + " has been added!");
var space = " ";
_.each(pods, function(value, key) {
key + space;
return space + payload.firstName + payload.secondName;
});
});
});
router.route('/pods').get(function(request, response) {
//console.log("We reached the POD page -- Yay! :D");
response.status(200).send("Server unavailable");
});
app.use('/', router);
app.listen(port, function () {
console.log('App listening on port %s', port);
});
I've checked over my code countless times and I can't seem to find the problem.
Here's the pod-handler file.
var PodDoc = require('../models/pods.js');
module.exports = {
save: save
}
function save(pod, callback){
var podToSave = new PodDoc();
podToSave.firstName = pod.firstName;
podToSave.lastName = pod.lastName;
/*podToSave.skills = pod.skills;
podToSave.avatarUrl = pod.avatarUrl;
podToSave.address = {
number: pod.address.number,
lineOne: pod.address.lineOne,
lineTwo: pod.address.lineTwo,
postcode: pod.address.postcode
}
podToSave.phoneNumbers = {
mobile: pod.phoneNumbers.mobile,
landline: pod.phoneNumbers.landline
}*/
podToSave.save(function(err){
if(err){
console.log(err);
} else {
console.log("Working");
callback();
}
})
}
When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database
If i understand correctly, you want to open this url in browser, and expect to have a record John in database.
Change router request type to GET, this
router.route('/pods/add').post(/*omitted*/);
to this
router.route('/pods/add').get(/*omitted*/);
Server is expecting POST request, but browser cannot handle it without FORM element or ajax request, browsers usually uses GET request, i mean when you open your url, it send GET request to server
There may be a typo error as in the url you are using port 300 where as the port configured for localhost is 3000.
When I type in localhost:300/pods/add?firstName='John'
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
});