jedireza / hapi-node-postgres

:package: Wrap hapi requests with a pg connection
MIT License
31 stars 11 forks source link

Hapi 17 support #28

Open jedireza opened 6 years ago

jedireza commented 6 years ago

See: https://github.com/hapijs/hapi/issues/3658

siarcarse commented 6 years ago

Have you any notice about this?

jedireza commented 6 years ago

Nothing new yet, I've been time poor. A PR is welcome if anyone gets time before I do.

mikejerome commented 6 years ago

This is very rough but I needed this for a new project so maybe this will help someone get started...

'use strict';

const Hoek = require('hoek');
let Pg = require('pg');

const DEFAULTS = {
  connectionString: undefined,
  attach: 'onPreAuth',
  detach: 'response'
};

exports.plugin = {
  name: 'car-hapi-pg',
  register: function(server, options) {

    const config = Hoek.applyToDefaults(DEFAULTS, options);

    server.ext(config.attach, async (request, h) => {
      const client = new Pg.Client({connectionString: config.connectionString});
      await client.connect();
      console.log('connected to pg');
      request.pg = {
        client
      };

      return h.continue;
    });

    server.events.on(config.detach, (request, err) => {

      if (request.pg) {
        request.pg.client.end().then(() => console.log('client disconnected'));
      }
    });
  }
};