From 9af5886bfbf9ae2aec404658984192bd152885cf Mon Sep 17 00:00:00 2001 From: Florian Traverse Date: Wed, 10 Oct 2018 10:21:20 +0200 Subject: [PATCH] add `pg` option, a simple test and some doc --- README.md | 28 ++++++++++++++++++++++++++++ index.js | 6 +++++- test.js | 26 ++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e0c7705..b8cc399 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,34 @@ fastify.listen(3000, err => { }) ``` +### `pg` option +If you want to provide your own `pg` module, for example to support packages like [`pg-range`](https://www.npmjs.com/package/pg-range), you can provide an optional `pg` option with the patched library to use: + +```js +const fastify = require('fastify') +const pg = require("pg"); +require("pg-range").install(pg) + +fastify.register(require('fastify-postgres'), { + connectionString: 'postgres://postgres@localhost/postgres', + pg: pg +}) + +fastify.get('/user/:id', (req, reply) => { + fastify.pg.query( + 'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id], + function onResult (err, result) { + reply.send(err || result) + } + ) +}) + +fastify.listen(3000, err => { + if (err) throw err + console.log(`server listening on ${fastify.server.address().port}`) +}) +``` + ## Development and Testing First, start postgres with: diff --git a/index.js b/index.js index 115e16d..3c2e405 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,7 @@ 'use strict' const fp = require('fastify-plugin') -var pg = require('pg') +var defaultPg = require('pg') function transactionUtil (pool, fn, cb) { pool.connect((err, client, done) => { @@ -56,6 +56,10 @@ function transact (fn, cb) { } function fastifyPostgres (fastify, options, next) { + let pg = defaultPg + if (options.pg) { + pg = options.pg + } if (options.native) { delete options.native if (!pg.native) { diff --git a/test.js b/test.js index e4a50c1..c34dbcb 100644 --- a/test.js +++ b/test.js @@ -117,6 +117,32 @@ test('use native module', t => { }) }) +test('use alternative pg module', t => { + const altPg = require('pg') + t.plan(2) + + const fastify = Fastify() + + fastify.register(fastifyPostgres, { + connectionString: 'postgres://postgres@localhost/postgres', + pg: altPg + }) + + fastify.ready(err => { + t.error(err) + fastify.pg + .query('SELECT 1 AS one') + .then(result => { + t.ok(result.rows[0].one === 1) + fastify.close() + }) + .catch(err => { + t.fail(err) + fastify.close() + }) + }) +}) + test('fastify.pg.test namespace should exist', t => { t.plan(6)