Skip to content

Commit bd654ce

Browse files
committed
Add default behaviour when no name key in options
1 parent 31bc16e commit bd654ce

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

index.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,27 @@ function fastifyPostgres (fastify, options, next) {
1717
delete options.name
1818

1919
const pool = new pg.Pool(options)
20-
21-
if (!fastify.pg) {
22-
fastify.decorate('pg', {})
23-
}
24-
25-
fastify.pg[name] = {
20+
const db = {
2621
connect: pool.connect.bind(pool),
2722
pool: pool,
2823
Client: pg.Client,
2924
query: pool.query.bind(pool)
3025
}
3126

27+
if (name) {
28+
if (!fastify.pg) {
29+
fastify.decorate('pg', {})
30+
}
31+
32+
fastify.pg[name] = db
33+
} else {
34+
if (fastify.pg) {
35+
console.warn('fastify-postgres has already registered')
36+
} else {
37+
fastify.pg = db
38+
}
39+
}
40+
3241
fastify.addHook('onClose', (fastify, done) => pool.end(done))
3342

3443
next()

test.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const test = t.test
55
const Fastify = require('fastify')
66
const fastifyPostgres = require('./index')
77

8-
test('fastify.pg namespace should exist', t => {
8+
test('fastify.pg.test namespace should exist', t => {
99
t.plan(6)
1010

1111
const fastify = Fastify()
@@ -26,6 +26,25 @@ test('fastify.pg namespace should exist', t => {
2626
})
2727
})
2828

29+
test('fastify.pg namespace should exist when name option not configure', t => {
30+
t.plan(5)
31+
32+
const fastify = Fastify()
33+
34+
fastify.register(fastifyPostgres, {
35+
connectionString: 'postgres://postgres@localhost/postgres'
36+
})
37+
38+
fastify.ready(err => {
39+
t.error(err)
40+
t.ok(fastify.pg)
41+
t.ok(fastify.pg.connect)
42+
t.ok(fastify.pg.pool)
43+
t.ok(fastify.pg.Client)
44+
fastify.close()
45+
})
46+
})
47+
2948
test('should be able to connect and perform a query', t => {
3049
t.plan(4)
3150

0 commit comments

Comments
 (0)