nswbmw / koa-mongo

MongoDB middleware for koa, support connection pool.
145 stars 31 forks source link

Check for mongodb connection #15

Closed activexJ closed 5 years ago

activexJ commented 7 years ago

Hi I need to check whether mongo db connection is availalbe or not and then only i want to use it as middleware or throw error. How to do this with koa-mongo. Currently If there is no mongodb connection the app goes not responding with 500 error code.

yesley commented 7 years ago

You could achieve it with simple middleware made by yourself. Something like this (for old node.js versions you could use promises or generators instead of async/await):

// db-middleware.js

const { MongoClient } = require('mongodb');

module.exports = function (url) {
    return async function (ctx, next) {
        try {
            ctx.db = await MongoClient.connect(url);
        } catch (e) {
            ctx.body = {
                success: false,
                error: 'Database connection error',
            };

            return;
        }

        await next();

        ctx.db && ctx.db.close();
    };
};
// index.js

const Koa = require('koa');
const db = require('db-middleware.js');

const app = new Koa();

app.use(db('mongodb://localhost:27017/test'));
app.listen(3000);
nswbmw commented 5 years ago

v1.5.0 fixed and throw a connection error, btw, you may use ctx.mongo.isConnected() check for mongodb connection.