Get data from RDS PostgreSQL in Lambda function with nodejs - postgresql

Problem I try get data from RDS PostgreSQL via Lambda function with Nodejs but response return is message
Execution result: failed with "errorMessage": "2017-07-05T15:05:27.425Z 596fdf39-6193-11e7-9176-f58796899f9b Task timed out after 3.00 seconds" }
This snip code:
const pg = require('pg');
exports.handler = (event, context, callback) => {
var conn = "pg://string connect database";
var client = new pg.Client(conn);
client.connect();
var resss = [];
var idUser = 2;
var query = client.query({
text: 'SELECT * from users where id= $1',
values: [idUser]
});
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
var jsonString = JSON.stringify(result.rows);
var jsonObj = JSON.parse(jsonString);
resss.push(jsonObj);
client.end();
context.done(null, jsonObj);
});
callback(null, resss);
};
<

Related

Nodejs mongoclient collection export

This is connection.js
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback) {
if (db_singleton) {
callback(null,db_singleton);
} else {
var connURL = "mongodb://localhost:27017/testdb";
MongoClient.connect(connURL,function(err,db){
if(err)
console.log("Error creating new connection "+err);
else
{
db_singleton=db;
console.log("created new connection");
}
callback(err,db_singleton);
});
}
};
module.exports = getConnection;
And this is product.js
var getConnection = require('../../connection.js');
var products = null;
getConnection(function(err,db) {
var collection = db.collection("products");
collection.find().toArray(function(err, productsDB) {
products = productsDB;
})
});
console.log(products);
module.export = products;
console.log(products) is always null.
But it should be object.I would like to cache variable when server starts.

ProxyConnectionError when connecting as Anonymous

I have developed an operator to retrieve information from Orion Context Broker.
It works perfectly when I'm loggin but if I try to enter as anonymous (with the embedded URL) in a incognito window, the operator raises the next error:
(link to the image): http://i.stack.imgur.com/jxMkr.png
This is the code:
var doInitialSubscription = function doInitialSubscription() {
this.subscriptionId = null;
this.ngsi_server = MashupPlatform.prefs.get('ngsi_server');
this.ngsi_proxy = MashupPlatform.prefs.get('ngsi_proxy');
this.connection = new NGSI.Connection(this.ngsi_server, {
ngsi_proxy_url: this.ngsi_proxy
});
console.log("Send initial subscription");
var types = ['SMARTMETER'];
var entityIdList = [];
var entityId;
entityId = {
id: '.*',
type: 'SMARTMETER',
isPattern: true
};
entityIdList.push(entityId);
var attributeList = null;
var duration = 'PT3H';
var throttling = null;
var notifyConditions = [{
'type': 'ONCHANGE',
'condValues': condValues
}];
var options = {
flat: true,
onNotify: handlerReceiveEntity.bind(this),
onSuccess: function (data) {
console.log("Subscription success ID: "+data.subscriptionId);
this.subscriptionId = data.subscriptionId;
this.refresh_interval = setInterval(refreshNGSISubscription.bind(this), 1000 * 60 * 60 * 2); // each 2 hours
window.addEventListener("beforeunload", function () {
this.connection.cancelSubscription(this.subscriptionId);
}.bind(this));
}.bind(this),
onFailure: function(data) {
console.log(data);
}
};
console.log("Now creating subscription...");
this.connection.createSubscription(entityIdList, attributeList, duration, throttling, notifyConditions, options);
};
Any idea of what is wrong?
According to user comments on the question, updating to Orion 0.19.0 (following the DB upgrade procedure detailed here) solves the problem.

Check how many rows retrieved in PostgreSQL (node.js)

I would like to know how can you check the row count of the query in PostgreSQL in node.js
I have this code for the meantime.
var client = new pg.Client(conString);
client.connect();
var query = client.query("SELECT * FROM users");
query.on('row', function(row) {
console.log(row);
});
var client = new pg.Client(conString);
client.connect();
client.query("SELECT * FROM users", function(err, result) {
console.log("Row count: %d",result.rows.length); // n
});
Another options is to use the rowCount property! Like this:
var pg = require('pg');
var pgClient = new pg.Client();
pgClient.connect();
var pgQuery = pgClient.query("SELECT * FROM information_schema.tables;");
pgQuery.on('error', function(err) {
pgClient.end();
console.error(err);
});
pgQuery.on('end', function(result) {
pgClient.end();
console.log(result.rowCount);
});
or like this:
var pg = require('pg');
var pgClient = new pg.Client();
pgClient.connect();
var pgQuery = pgClient.query("SELECT * FROM information_schema.tables;", function(err, result) {
pgClient.end();
if (err) return console.error(err);
console.log(result.rowCount);
});

How to debug Node.js crashes after the crash event on FreeBSD 8.2?

I have a Node.js HTTP server running that counts things (results are stored in MongoDB using Mongoose). Here it is, in brief:
var Elbrus = (function() {
var my = {},
my.try = function(testId, tag) {
var testresult = new TestTry();
testresult.testId = testId;
testresult.tag = tag;
testresult.save();
};
my.score = function(testId, tag) {
var testresult = new TestScore();
testresult.testId = testId;
testresult.tag = tag;
testresult.save();
}
return my;
}());
http.createServer(function (req, res) {
var urlObj = url.parse(req.url, true);
if (urlObj.query["score"]) {
res.writeHead(200, {'Content-Type': 'image/gif'});
Elbrus.score(urlObj.query["testId"],urlObj.query["score"]);
res.end();
}
else if (urlObj.query["try"]) {
res.writeHead(200, {'Content-Type': 'image/gif'});
Elbrus.try(urlObj.query["testId"],urlObj.query["try"]);
res.end();
}
}).listen(8080, "myserver.com");
TestTry and TestScore are Mongoose models.
This server will run for some hours, sometimes up to 12, and then crash. How can I begin to understand what the issue is? I'm on FreeBSD 8.2 and do not have mdb, although I do have gdb.

Error in connecting database (mongo and nodejs)

I want build a class for wrapping database connection. This is my code ('db.js' file):
var mongodb = require('mongodb');
var Class = function() {
this.db = null;
var server = new mongodb.Server('127.0.0.1', 27017, {auto_reconnect: true});
db = new mongodb.Db('myDB', server);
db.open(function(error, db) {
if (error) {
console.log('Error ' + error);
} else {
console.log('Connected to db.');
this.db = db;
}
});
};
module.exports = Class;
Class.prototype = {
getCollection: function(coll_name) {
this.db.collection(coll_name, function(error, c){ // <--- see error below
return c;
});
}
}
exports.oid = mongodb.ObjectID;
Then, my test code ('test.js' file):
var DB = require('./db');
var myDB = new DB();
myDB.getCollection('myCollection'); // <--- error: Cannot call method 'collection' of null
You are missing "this" in front of "db". eg:
this.db = new mongodb.Db('myDB', server);
And the line next to it.