Cannot insert record to PostgreSQL in Bluemix - node.js

I try to get postgresql work with Node.js in Bluemix platform. However, there is a problem. I tried to use the code described in https://www.ng.bluemix.net/docs/#starters/nodejs/index.html#PostgreSQL.
I can run the app I written successfully in local environment. However, it is not functioning properly in Bluemix platform.
Following is the code describing what I have done:
var recordVisit = function(req, res) {
/* Connect to the DB and auth */
pg.connect(psql,
function(err, client, done) {
if (err) {
return console.error('Error requesting client', err);
}
console.log(req.ip);
client.query('insert into ips(ip, ts) values($1, $2)', [req.ip, new Date()],
function(err, result) {
if (err) {
done();
return console.error('Error inserting ip', err);
}
client.query('select count(ip) as count from ips where ip=$1',
[req.ip],
function(err, result) {
done();
if (err) {
return console.error('Error querying count', err);
}
console.log("You have visited " + result.rows[0].count + " times")
// res.writeHead(200, {'Content-Type': 'text/html'});
// res.end();
}
);
}
);
}
);
};
It is following the code from the bluemix document. The result of the visit count in Bluemix always be zero (0). But the result in local environment is okay. And I did not get any error from the Bluemix platform. So I assume that the visit record can be inserted. However, seems that it is not.
Can anyone have any pointer for me to solve this problem?

I tried to insert more logging into the insert function. I found that the variable req.ip becomes undefined in the result of INSERT SQL in Bluemix platform.
So I added a local variable to store the ip of the request in order to keep the content.

Related

How to get current logged in user id in odoo and node js

I want to display the current logged in user-id. I'm using odoo-xmlrpc node module to connect my express and odoo application.
odoo.execute_kw("res.users", "search_read", params, function( err,result) {
if (err) {
return console.log(err);
}
res.json(result);
});
here I can return all users. But I want to return the current user. I have found this
article which is done with python
The connect method returns the current logged user-id uid after a successful login.
You can get it there:
odoo.connect(function (err, uid) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
console.log('uid', uid)
});

Node js oracle module: the console log statement not working when select query is executed

I have installed the node-oracle module and have connected to an oracle database successfully. But, I have a problem when I execute a select query. My code is below (the file name is tests-connection.js):
var oracle = require('./');
var connectData = {
hostname: "myhost",
port: 1521,
database: "mydb", // System ID (SID)
user: "usertest",
password: "mypass"
}
oracle.connect(connectData, function(err, connection) {
if (err) { console.log("Error connecting to db:", err); return; }
connection.execute("SELECT systimestamp FROM DUAL", [], function(err, results) {
if (err) { console.log("Error executing query:", err); return; }
console.log(results); //This statement's not working
connection.close(); // call only when query is finished executing
});
});
The output in Node.js command prompt (nothing):
C:\xampp\htdocs\motcua.dev\public\socket.io\node_modules\oracle>node tests-connection
C:\xampp\htdocs\motcua.dev\public\socket.io\node_modules\oracle>
I have tried to update a record and it works, but when I execute a select query I do not see any output in the console log statement. The terminal is empty until the code that is executing is finished.
How can one fix this problem?
Thanks

Save to database on change, angular and node js

I'm converting an MS Access database to a webapp. I'm using Angular JS, Node JS with the express framework and MySQL as database.
In ms access you don't have any edit/save features. When you edit something, the database changes instantly. I like this. Feels smooth. So I want to have this the same way in the web app. My question is. Will there be any problems with this approach in my webbapp?
This is a piece of my node js code which updates the database with a restcall:
/*
Post /api/products/ HTTP/1.1
*/
exports.editProduct = function(req, res) {
console.log(req.body);
var post = [{title_en: req.body.title_en},req.params.id];
if (connection) {
connection.query("UPDATE products SET ? WHERE id = ?", post, function(err, rows, fields) {
if (err) throw err;
res.contentType('application/json');
res.write(JSON.stringify(rows));
res.end();
});
}
};
And on the client side I use the a the $resource object
$scope.save = function(){
$scope.product.$save(function(){
console.log('Save successfull);
});
};
And in the view. I simply have inputs with ng-change:
<input ng-model="product.title_en" ng-change="save()".
Will this work good in production mode with a couple hundred users? Is the chances of blocking/crashing etc?
The only thing I see is if (err) throw err;
if there is an error the server crash so change it with a json response with a 500 status.
By the way express has a build-in way to output json
It's better off to validate title_en and id
exports.editProduct = function(req, res) {
console.log(req.body);
var post = [{title_en: req.body.title_en},req.params.id];
if (connection) {
connection.query("UPDATE products SET ? WHERE id = ?", post, function(err, rows, fields) {
if (err) {
return res.json(500,{ error: 'Cannot update the product' });
}
res.json(200,rows);
});
}
an other thing try to use restangular instead of resource it's a lot of fun :)
};

app.render() not displaying in browser

I'm trying to use app.render() to display a jade file in the browser. In the following code, the html is displayed to the console correctly, but the browser never shows the related file.
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
});
EDIT:
I have this handler:
app.get('/unavailable', display.unavailable);
Then beneath this code in the same file (app.js) I have this:
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
else
conn = sqlconn; //save the sql connection globally for all client's to use
});
So, what I want to happen is when the err happens with the SQL connection, the /unavailable handler is executed and a static html page is displayed that says the service is down. However, because the error occurs on the server, and not the client, I don't have access to a response object at that time. I'm trying to artifically manufacture the client 'redirecting' to /unavailable in their browser to see the message.
Obviously you don't send the html to the browser. Use res.render inside a route without callback, i.e.
res.render('unavailable', {title: 'Unavailable'});
or send the result of rendering like here:
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
res.send(html);
});
Read more about the difference here:
What's the difference between "app.render" and "res.render" in express.js?
save a global var sqlOK = false, set it in sql.open callback, and redirect to /unavailable if you get a request while sqlOK is not true. you were also missing brackets around the else statement.
var sqlOK = false;
app.get('/unavailable', display.unavailable);
app.get('*', function(req, res, next){
if(!sqlOK){
return res.redirect('/unavailable');
//return res.send(500)
};
next();
});
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
} else {
conn = sqlconn; //save the sql connection globally for all client's to use
sqlOK = true
}
});

Node.js app becomes unresponsive if I reload multiple times in quick succession

I'm developing a node.js app that displays a single page with map data (which will eventually be updated using an .ajax call).
Right now, my code looks like this:
app.get('/', function(req, res) {
postgres.retrieve('SELECT * FROM settings', function(err, proj_data){
if (err){
res.send(500);
}
else{
postgres.retrieve('SELECT * FROM report ORDER BY ordering', function(err, report_data){
res.render('map', {project: proj_data[0], report: report_data});
});
}
});
and postgres.retrieve is a function that uses the node-postgres client:
retrieve: function(query, complete){
pg.connect(connection, function(err, client, done){
client.query(query, function(err, results){
if (err){
done();
return complete(err, null);
}
else {
done();
return complete(null, results.rows);
}
});
});
},
Currently, if I hit f5 10 times (over, say, 10 seconds), everything seems to respond fine, but right after, memory usage goes way up and the app becomes totally unresponsive. I'm wondering if there's something in my code that's causing this problem.
Thanks!
Oops, it seems that this is an issue in Node v0.10.0 +
https://github.com/joyent/node/issues/5108

Resources