1.0.2 • Published 4 years ago

hapi-pgsql v1.0.2

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

This Hapi Plugin creates a Connection to PostgreSQL when your server starts up and makes it available anywhere in your app's route handlers via request.pgsql.

When you shut down your server (e.g. the server.stop in your tests) the connection is closed for you.

This plugin supports Hapi v17 and above. For older Hapi version, might consider a plugin that I love using before building this https://www.npmjs.com/package/hapi-postgres-connection

Release

1.0.0 - Inital Repo

1.0.1 - Updated to support Hapi 19, bumped NodeJS to version 12+

1.0.2 - Optimized Package Size

1. Download / Install with npm / Yarn

npm install --save hapi-pgsql
yarn add hapi-pgsql

2. Add the plugin to your Hapi Server

in your server:

await server.register({
    plugin: require('hapi-pgsql'),
    options: {
        database_url: 'postgresql://username:password@hostname/database',
    }
})

Now all your route handlers have access to Postgres via: request.pgsql

3. Using Postgres Client in your Route Handler

server.route({
    method: 'GET',
    path: '/',
    handler: async (request, h) => {
        const time = await request.pgsql.query('SELECT NOW()')
        return `Hello World! Time: ${time.rows[0].now}`;
    }
});

4. Using Postgres Client with param meters escape in your Route Handler

server.route({
    method: 'POST',
    path: '/login',
    handler: async (request, h) => {
        const todos = await request.pgsql.query(
            `SELECT * FROM user WHERE email = $1 AND password = $2 LIMIT 1`, 
            [request.payload.email, request.payload.password]
        )
        return todos.rows[0]
    }
});
1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago