expressmongooselocomotivejs

Locomotivejs Check MongoDB connection before all actions


I want to check MongoDB connection and reconnect to it if it's not in "connected" state, before any query is made to it from withing a LocomotiveJS server. A possible way is to add have it in the before filters. Is there any way to define a before filter for all controllers?


Solution

  • I believe you can use express (and LocomotiveJS is on to of it) way of handling requests.

    In your config/environments/all.js (the best somewhere before all this.use declaration starts)

    this.use(function(req, res, next) {
        if (!isMongoInConnectedState()) {
            setMongoToConenctedState();
        }
        next();
    });
    

    This way the function will be called for every request made to the server. Calling next() just passes processing of the request for next handlers (Locomotive controllers in your case).

    You can also specify requests where this checking function should be called:

    this.get(/^\/admin\/.*/, function(req, res, next) {
        if (!isMongoInConnectedState()) {
            setMongoToConenctedState();
        }
        next();
    });
    

    Here, check will be made only for /admin/* GET urls.

    The order of runing this.use or this.get function is important - first declared handler will be called first during request processing.