how to check monogdb database connection - javascript

Working with Node.js(monogdb, express and other modules)
I'm wondering if there is a mongoose method for database connection, something like if I open a connection var db = mongoose.connect('mongo://localhost/members'); then I can db.on('close', function(){ /*do stuffs here*/}).
Basicly, the function below does the job of getting a user list from database and logging when database connection is closed.
So I need something in the if() to check database connection or whatever just unable to get data while its off and make a logging. I tried if(docs != null) it seems just off tho. Any advice would be much appreciated!
var logger = require('bunyan');
var log = new logger({
name: "loggings",
streams: [
{
level: 'error',
path: 'test.log',
}
],
serializers: {
err: logger.stdSerializers.err,
}
});
function(req, res){
memberModel.find(function(err, docs){
if (/*connection is closed*/) {
res.render('users.jade', { members: docs });
}else{
try {
throw new DatabaseError ("Error!");
} catch (err){
log.warn({err: err}, "Check database connection!");
}
res.render('index.jade');
};
});
};

Why are you checking in the place you are for the database connection being closed? If it is closed at that point, then it is likely that docs will be null. I think checking
if (!err) {
res.render('users.jade', { members : docs });
} else {
/* throw err, etc */
is a reasonable course to take.
Since you want to log when the database connection is closed, why not attach a logging function to the Db's "close" event?
If I've misunderstood and checking for the connection's state is what you really want, then I'd recommend playing around with the properties of:
http://mongoosejs.com/docs/api.html#connection_Connection
(hit the "show code" button). The connection's _closeCalled property looks like it may be what you want to check.

You can use mongoose events that will get fire whenever your server get disconnected:
mongoose.connection.on('error', function (err) {
console.log('Mongoose default connection error: ' + err);
//HERE SERVE YOUR DISCONNECT WARNING PAGE AND LOGGER
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
//HERE SERVE YOUR DISCONNECT WARNING PAGE AND LOGGER
});

var uri = 'mongodb://localhost/user1';
var promise = mongooose.connect(uri,{
useMongoClient: true,
});
promise.openUri(uri,function(errr,db){
if(errr){
throw errr;
}else{
console.log("Connection Successfull");
glo_db = db;
}
});
Above could needs to be written for the newer version of mongoose and would throw error if any error is found while connecting to a database.
Check here

Related

WebSocket stops working in Vue/Node application

I have a Node/Vue application. I am consuming a WebSocket from Binance, a crypto exchange. I can see the quotes on the server console as I log them, I can send them to the browser for a short period of time before the client stops logging them.
Browser just using WebSocket API
Node using ws library
Node code, this I am running as it's own service as its just this.
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.on('connection', function connection(ws){
console.log("Connected a new client");
ws.send(data);
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
})
On the Client side I am using Vue and in the app.js file I have this on the created hook.
let socket = new WebSocket("ws://localhost:5002")
socket.addEventListener('message', function(event){
let quotes = JSON.parse(event.data);
console.log(quotes.p)
});
socket.addEventListener('error', function(event){
console.log("closing because " + event);
})
Right now I am only listening to the consoles in the above app.vue file.
What I see in the browser console is a lot of quotes, then they stop after a second or 2. There can be over a thousand quotes in some times. Then on occasion I see a console.log('created') that I have in a child component of app.vue. In many cases this is the last thing in the console after hundreds of quotes.
In the console.log for the server I see a lot of sessions being created with one page refresh. So much that it fills my console.
So I'm not sure I am creating the connections correcly, I am not sure if Vue is somehow stopping the console.log's?
I don't see any errors anywhere and the entire time in my server console the Binance API continues streaming.
you have to write server event listener outside binance on message handler;
then you can pass messages from binance to the server by emitting new event to the server
on receiving message from binance you can send data to all connection on the server
Or Try this code I think it will work :
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
server.on('connection', function connection(ws){
console.log("Connected a new client");
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
})

Socket.io failing authorization does not retry to reconnect

I am using socket io with a simple token auth method (server side):
io.use(function(socket, next){
var handshake = socket.request;
if(token == handshake._query.token)
{
console.log('Client authorized');
next();
}
else
{
console.log('Client not authorized');
next(new Error('not_authorized'));
socket.disconnect();
}
});
The problem is that if the client failed the first time authorization (wrong token), it does not retry to connect any more, even If I send a manual new connection it will not recconect until a total page refresh.
Cliend side:
var socket = io.connect(this.adress, {query: 'token=123456789', transports:['websocket', 'polling'] });
socket.on('error', function(err){
console.log(err);
if(err == 'not_authorized')
{
console.log('gettin toke');//NOT ENTERING HERE
}
PS.connected = false;
});
How can I retry reconnect with another parameter?
Workaround, set this variables againg to retry connecting:
PS.socket.socket.connecting = false;
PS.socket.socket.options.query = 'token='+tok;
According to the documentation sample you should not use socket.disconnect();. Your client-side error event does not fire exactly because of this line.
Edit:
You may also try to set forceNew to true in connection options when reconnecting:
var socket = io.connect(this.adress, {
query: 'token=123456789',
transports:['websocket', 'polling'],
forceNew: true
});

Catching errors from mongoose queries in express

How can I catch error from mongoose queries. In my routes I got something like this:
// router.js
router.route('/signup')
.post(function(req, res) {
var profile = new Profile(); // create a new instance of the profile model
profile.username = req.body.username;
profile.password = profile.generateHash(req.body.password);
profile.save(function(err) {
if (err) { // (A)
throw new Error('user/create error'));
} else {
res.json(200, { user_token: profile._id, username: profile.username });
}
});
});
and in my app were I set up my routes I got this:
// app.js
var router = require('./app/routes/routes');
// global-error handling middleware
app.use(function(err, req, res, next) {
console.log('Some error is happening.');
res.json(500, {status: 500, message: err.message});
});
If I generate a error so I get to line // (A) in my code above I get a stack trace and node.js exists. I want to catch the error In my error handler. How do I do this?
Well, you are already in the request handler, and you already have access to the error produced while saving the profile object. So, there is no need to throw an exception here. You can already handle the problem.
The most likely scenario here is to send a response to the user indicating that the saving of the profile failed.
function(req, res) {
profile.save(function(err) {
if (err) { // (A)
res.send(500, {message: 'Failed to save profile'}
} else {
res.json(200, { user_token: profile._id, username: profile.username });
}
});
}
And that's it. Your client will receive a 500 status error and this evidently represents a problem that your client will need to deal with, like notifying the user, doing a retry, etc, etc, etc.
you can use Promise-like error handling. mongoose permits to use promises on its methods:
profile.save().then((doc) => {
// if done correctly
}).catch((err) => {
// catch error if occurs
// handle error
});
you can read more about mongoose built-in promises there.

Apigee error when behind gateway proxy

I'm creating an HTML 5 client to app services, however our app services are enterprise so behind an apigee gateway proxy ( not directly through api.usergrid.com).
I'm initializing like this:
$(function() {
var client = new Apigee.Client({
orgName:'myorg',
appName:'sandbox',
monitoringEnabled:false,
URI:'https://prod.OURURL.com/appservices/v1'
});
var username = "myusername";
var password = "mypass";
client.login(username, password,
function (err) {
if (err) {
console.log('There was an error logging you in.');
} else {
//login succeeded
client.getLoggedInUser(function(err, data, user) {
if(err) {
//error - could not get logged in user
console.log("error on lvl2");
} else {
if (client.isLoggedIn()){
appUser = user;
console.log('data')
// showFullFeed();
}
}
});
}
}
);
});
I'm immediately getting:
Error: Apigee APM configuration unavailable.
and then of course:
There was an error logging you in.
using the trace tool in the proxy I can see this errorr on the request to /proxy_path/org/app/apm/apigeeMobileConfig
{"timestamp":"1398263318219","duration":"0","error":"illegal_argument","exception":"java.lang.IllegalArgumentException","error_description":"JSON source MUST not be null"}
of course this is all called by the above code.
thank you in advance.
[EDIT FOR MORE INFORMATION]
Just tested with my own private org, so not setting the options.URI param, the second log message is normal as I had not created the app user, however the initialization is NOT working on the enterprise org, so this:
var client = new Apigee.Client({
orgName:'myorg',
appName:'sandbox',
monitoringEnabled:false,
URI:'https://prod.OURURL.com/appservices/v1'
});
is returning the APM error.
It seems you need to enable some of the options in the app services app ( inthe configuration option) for this api call to return something, thus enabling the sdk.

How to check if mongos connection still alive in Node.JS?

Let's imagine we have Node.JS app which is connecting to the Mongos process. But suddenly Mongos failed. How our app could now about it?
var db = null;
mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb) {
if(err) throw err;
db = mydb
});
..... on response we have .....
db.collection('test_collection', function(err, collection){
collection.find({}).toArray(function(err, documents){
// doing some work here
// but if Mongos failed, we are blocked on this stage
});
});
Would you not want to do the same thing that you're doing at connect, but within the function?
i.e.
...
collection.find({}).toArray(function(err, documents) {
if(err) {
throw err; //or do something equivalent. It doesn't really matter if the connection has failed, as it will still throw an error.
} else {
///continue processing
}
....
Alternatively, if you use a 3rd party mongo manager, such as mongoose, you can do something like this globally:
mongoose.connect('mongodb://' + config.mongo.host + '/' + config.mongo.db);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error: '));

Categories

Resources