Skip to content

Commit 9445b88

Browse files
temsacemremengu
authored andcommitted
add pg option, a simple test and some doc (#30)
1 parent 772ff91 commit 9445b88

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

README.md

+28
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,34 @@ fastify.listen(3000, err => {
175175
})
176176
```
177177

178+
### `pg` option
179+
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:
180+
181+
```js
182+
const fastify = require('fastify')
183+
const pg = require("pg");
184+
require("pg-range").install(pg)
185+
186+
fastify.register(require('fastify-postgres'), {
187+
connectionString: 'postgres://postgres@localhost/postgres',
188+
pg: pg
189+
})
190+
191+
fastify.get('/user/:id', (req, reply) => {
192+
fastify.pg.query(
193+
'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
194+
function onResult (err, result) {
195+
reply.send(err || result)
196+
}
197+
)
198+
})
199+
200+
fastify.listen(3000, err => {
201+
if (err) throw err
202+
console.log(`server listening on ${fastify.server.address().port}`)
203+
})
204+
```
205+
178206
## Development and Testing
179207

180208
First, start postgres with:

index.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict'
22

33
const fp = require('fastify-plugin')
4-
var pg = require('pg')
4+
var defaultPg = require('pg')
55

66
function transactionUtil (pool, fn, cb) {
77
pool.connect((err, client, done) => {
@@ -56,6 +56,10 @@ function transact (fn, cb) {
5656
}
5757

5858
function fastifyPostgres (fastify, options, next) {
59+
let pg = defaultPg
60+
if (options.pg) {
61+
pg = options.pg
62+
}
5963
if (options.native) {
6064
delete options.native
6165
if (!pg.native) {

test.js

+26
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,32 @@ test('use native module', t => {
117117
})
118118
})
119119

120+
test('use alternative pg module', t => {
121+
const altPg = require('pg')
122+
t.plan(2)
123+
124+
const fastify = Fastify()
125+
126+
fastify.register(fastifyPostgres, {
127+
connectionString: 'postgres://postgres@localhost/postgres',
128+
pg: altPg
129+
})
130+
131+
fastify.ready(err => {
132+
t.error(err)
133+
fastify.pg
134+
.query('SELECT 1 AS one')
135+
.then(result => {
136+
t.ok(result.rows[0].one === 1)
137+
fastify.close()
138+
})
139+
.catch(err => {
140+
t.fail(err)
141+
fastify.close()
142+
})
143+
})
144+
})
145+
120146
test('fastify.pg.test namespace should exist', t => {
121147
t.plan(6)
122148

0 commit comments

Comments
 (0)