'How to register pg-promise with hapi

I try to register pg-promise as hapi plugin. However, the following error occurred.

TypeError: Cannot read properties of undefined (reading 'name')
at internals.Server.register (/home/kim.js/pgpromise/node_modules/@hapi/hapi/lib/server.js:456:42)
at init (/home/kim.js/pgpromise/hapi-pgTest.js:22:16)

My code is as follows and I also attach a reference site.
Hapi Tutorial - Getting Started
Hapi Tutorial - Plugins

'use strict';

const promise = require('bluebird');
const Hapi = require('@hapi/hapi');
const Pg = require('pg-promise')();

const postgreSql = {
    host: '127.0.0.1',
    port: 5432,
    user: 'someone',
    password: 'my_password',
    database: 'my_db',
    table_schema: 'public',
};

const init = async () => {
  const server = Hapi.server({
      port: 3000,
      host: '192.168.9.23'
  });  

  await server.register([{    // ERROR is Here !!
    plugin: Pg,
    options: {
      promiseLib: promise
    }
  }]);

  server.route({     
      method: 'GET',
      path: '/',
      handler: async (request, h) => {
        let sql = 'SELECT FROM my_table limit 1';

        let result = await pgp.one(sql).catch(error => { console.log(sql); });
        return result;
      }
  });

  const pgp = Pg(postgreSql);

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();


Solution 1:[1]

English is not my first language, so please understand if the sentence is weird.

In my project, I used a plug-in called hapi-pg-promise before, but Hang occurred with hapi v20.

My mistake was that I try register the module, not the plugin. So I referred to hapi plugin doc and modified my code by referring to hapi-pg-promise source code.

Make My hapi-pg-promise

'use strict';

/* this is original source
const Hoek = require('hoek');
const PgPromise = require('pg-promise');
*/

const Hoek = require('@hapi/hoek');
const PgPromise = require('pg-promise')();
const pkg = require('./package.json');

const DEFAULTS = {
    init: {},
    cn: undefined
};

module.exports = {
  pkg,
  register: async function (server, options) {

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

      const pgp = require('pg-promise')(opts.init);
      const db = pgp(opts.cn);

      server.ext('onPreHandler', (request, h) => {
          request.db = db;
          return h.continue;
      });

      server.expose('db', db);

      server.events.on('stop', pgp.end);
  }
};

After that, I registered the plugin and it worked :)

/* NOT this
const Pg = require('pg-promise')();
*/
const Pg = require('./myPlugins/my-hapi-pg-promise');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1