drboom-pg

0.3.1 • Public • Published

Dr. Boom: Postgres

npm i pgboom

Auto-cast errors from pg into Hapi HTTP Errors.

Example / Boilerplate

Plugin registration boilerplate:

var hapi = require('hapi');
var config = require('./config.json');
var Boom = require('boom');
 
var server = new hapi.Server();
server.connection(config);
 
server.register([{
    register: require('drboom')(), 
    options: {
        plugins: [require('drboom-pg')({getNull404: true,
            extendConditions: {
                '2201W': function (err) {
                    return Boom.badRequest('Invalid pagination values');
                }
            },
            extendCategories: {
                '28': function (err) {
                    return Boom.unauthorized('Invalid credentials');
                }
            }
        })]
    },
}, function (err) {
    server.log(['startup'], 'Loaded pgboom plugin');
    server.start(function (err) {
        //...
    }
});

Now, you can pass your postgres errors right on through to hapi reply!

function someHandler(request, reply) {
    pg.query("SELECT id FROM request.params.id", function (err, results) {
        reply(err, results.rows);
    });
});

Options

getNull404: Boolean. If the handler request method is GET, and postgres doesn't pass a result, throw a 404 Not Found error regardless of there not being a postgres error. Default: False

extendConditions: Object. Keys of postgres error codes, mapped to functions that return Boom objects.

extendCategories: Object. Keys of the first 2 digits of error codes, mapped to functions that return Boom objects.

Default Conditions and Categories

var condition = {
    '23505': function (err) {
        return Boom.conflict(util.format("Failed relationship constraint: %s", err.constraint));
    }, 
    '42501': function (err) {
        return Boom.forbidden(err.toString());
    }
}
 
var category = {
    '08': function (err) {
        return Boom.serverTimeout('Database unavailable');
    },
    '53': function (err) {
        return Boom.serverTimeout('Database unavailable');
    },
    '22': function (err) {
        return Boom.badData(err.toString());
    },
    '23': function (err) {
        return Boom.badData(err.constraint);
    }
}

I'll gladly accept pull requests!

Package Sidebar

Install

npm i drboom-pg

Weekly Downloads

3

Version

0.3.1

License

MIT

Last publish

Collaborators

  • fritzy