Skip to content

Commit cedc35e

Browse files
authored
chore: code cleanup (#110)
* chore: upgrade package dependencies * chore: add a `lint:fix` command * test: add new test cases and make test names more explicit * refactor: improve code readability * chore: upgrade package dependencies * refactor (test): typo fix * refactor (test): apply @mcollina suggestion to use await fastify.ready()
1 parent 1d87747 commit cedc35e

5 files changed

+123
-46
lines changed

index.js

+14-14
Original file line numberDiff line numberDiff line change
@@ -102,19 +102,21 @@ function fastifyPostgres (fastify, options, next) {
102102
if (db[name]) {
103103
return next(new Error(`fastify-postgres '${name}' is a reserved keyword`))
104104
} else if (!fastify.pg) {
105-
fastify.decorate('pg', {})
105+
fastify.decorate('pg', Object.create(null))
106106
} else if (fastify.pg[name]) {
107107
return next(new Error(`fastify-postgres '${name}' instance name has already been registered`))
108108
}
109109

110110
fastify.pg[name] = db
111111
} else {
112-
if (!fastify.pg) {
113-
fastify.decorate('pg', db)
114-
} else if (fastify.pg.pool) {
115-
return next(new Error('fastify-postgres has already been registered'))
116-
} else {
112+
if (fastify.pg) {
113+
if (fastify.pg.pool) {
114+
return next(new Error('fastify-postgres has already been registered'))
115+
}
116+
117117
Object.assign(fastify.pg, db)
118+
} else {
119+
fastify.decorate('pg', db)
118120
}
119121
}
120122

@@ -125,13 +127,11 @@ function fastifyPostgres (fastify, options, next) {
125127
fastify.addHook('onRoute', routeOptions => {
126128
const transact = routeOptions && routeOptions.pg && routeOptions.pg.transact
127129

128-
if (!transact) {
129-
return
130-
}
131-
if (typeof transact === 'string' && transact !== name) {
132-
return
133-
}
134-
if (name && transact === true) {
130+
if (
131+
!transact ||
132+
(typeof transact === 'string' && transact !== name) ||
133+
(name && transact === true)
134+
) {
135135
return
136136
}
137137

@@ -140,7 +140,7 @@ function fastifyPostgres (fastify, options, next) {
140140

141141
if (name) {
142142
if (!req.pg) {
143-
req.pg = {}
143+
req.pg = Object.create(null)
144144
}
145145

146146
if (client[name]) {

package.json

+8-7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"types": "index.d.ts",
77
"scripts": {
88
"check-examples": "tsc --build examples/typescript/*",
9+
"lint:fix": "standard --fix",
910
"load-data": "docker exec -it fastify-postgres psql -c 'CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);' -U postgres -d postgres",
1011
"postgres": "docker run -p 5432:5432 --name fastify-postgres -e POSTGRES_PASSWORD=postgres -d postgres:11-alpine",
1112
"test": "standard && tap -J test/*.test.js && npm run test:typescript",
@@ -36,15 +37,15 @@
3637
"fastify-plugin": "^3.0.0"
3738
},
3839
"devDependencies": {
39-
"@tsconfig/node10": "^1.0.7",
40-
"@types/pg": "^8.6.0",
41-
"fastify": "^3.0.0",
42-
"pg": "^8.2.1",
40+
"@tsconfig/node10": "^1.0.8",
41+
"@types/pg": "^8.6.1",
42+
"fastify": "^3.21.5",
43+
"pg": "^8.7.1",
4344
"pg-native": "^3.0.0",
44-
"standard": "^16.0.0",
45-
"tap": "^15.0.2",
45+
"standard": "^16.0.3",
46+
"tap": "^15.0.10",
4647
"tsd": "^0.17.0",
47-
"typescript": "^4.0.2"
48+
"typescript": "^4.4.3"
4849
},
4950
"peerDependencies": {
5051
"pg": ">=6.0.0"

test/add-handler.test.js

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

3-
const t = require('tap')
4-
const test = t.test
3+
const { test } = require('tap')
54
const addHandler = require('../lib/add-handler')
65

7-
test('addHandler - ', t => {
8-
test('when existing handler is not defined', t => {
6+
test('The addHandler lib should return the right handlers structure', t => {
7+
t.test('When the existingHandler argument is undefined', t => {
98
t.plan(1)
109

1110
const handlers = addHandler(
@@ -15,7 +14,8 @@ test('addHandler - ', t => {
1514

1615
t.same(handlers, ['test'])
1716
})
18-
test('when existing handler is a array', t => {
17+
18+
t.test('When the existingHandler argument is an array', t => {
1919
t.plan(1)
2020

2121
const handlers = addHandler(
@@ -25,7 +25,8 @@ test('addHandler - ', t => {
2525

2626
t.same(handlers, ['test', 'again'])
2727
})
28-
test('when existing handler is a function', t => {
28+
29+
t.test('When the existingHandler argument is a function', t => {
2930
t.plan(2)
3031

3132
const stub = () => 'test'

test/initialization.test.js

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

3-
const t = require('tap')
4-
const test = t.test
3+
const { test } = require('tap')
54
const Fastify = require('fastify')
65
const pg = require('pg')
76
const fastifyPostgres = require('../index')
@@ -247,3 +246,36 @@ test('fastify.pg custom namespace should exist if a name is set', (t) => {
247246
t.ok(fastify.pg.test.Client)
248247
})
249248
})
249+
250+
test('fastify.pg and a fastify.pg custom namespace should exist when registering a named instance before an unnamed instance)', async (t) => {
251+
t.plan(10)
252+
253+
const fastify = Fastify()
254+
t.teardown(() => fastify.close())
255+
256+
await fastify.register(fastifyPostgres, {
257+
connectionString,
258+
name: 'one'
259+
})
260+
261+
await fastify.register(fastifyPostgres, {
262+
connectionString
263+
})
264+
265+
await fastify.ready().catch(err => t.error(err))
266+
267+
t.ok(fastify.pg)
268+
t.ok(fastify.pg.connect)
269+
t.ok(fastify.pg.pool)
270+
t.ok(fastify.pg.Client)
271+
272+
t.ok(fastify.pg.one)
273+
t.ok(fastify.pg.one.connect)
274+
t.ok(fastify.pg.one.pool)
275+
t.ok(fastify.pg.one.Client)
276+
277+
const result = await fastify.pg.query('SELECT NOW()')
278+
const resultOne = await fastify.pg.one.query('SELECT NOW()')
279+
t.same(result.rowCount, 1)
280+
t.same(resultOne.rowCount, 1)
281+
})

test/req-initialization.test.js

+60-17
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
'use strict'
22

3-
const t = require('tap')
4-
const test = t.test
3+
const { test } = require('tap')
54
const Fastify = require('fastify')
65
const fastifyPostgres = require('../index')
76
const { connectionString } = require('./helpers')
87

98
const extractUserCount = response => parseInt(JSON.parse(response.payload).rows[0].userCount)
109

11-
test('fastify postgress useTransaction route option', t => {
12-
test('queries that succeed provided', async t => {
10+
test('When we use the fastify-postgres transaction route option', t => {
11+
t.test('Should be able to execute queries provided to the request pg decorator', async t => {
1312
const fastify = Fastify()
1413
t.teardown(() => fastify.close())
1514

@@ -40,7 +39,8 @@ test('fastify postgress useTransaction route option', t => {
4039

4140
t.equal(extractUserCount(response), 2)
4241
})
43-
test('queries that succeed provided to a namespace', async t => {
42+
43+
t.test('Should be able to execute queries provided to a namespaced request pg decorator', async t => {
4444
const fastify = Fastify()
4545
t.teardown(() => fastify.close())
4646

@@ -73,7 +73,8 @@ test('fastify postgress useTransaction route option', t => {
7373

7474
t.equal(extractUserCount(response), 2)
7575
})
76-
test('queries that fail provided', async t => {
76+
77+
t.test('Should trigger a rollback when failing to execute a query provided to the request pg decorator', async t => {
7778
const fastify = Fastify()
7879
t.teardown(() => fastify.close())
7980

@@ -92,7 +93,43 @@ test('fastify postgress useTransaction route option', t => {
9293
fastify.get('/fail', { pg: { transact: true } }, async (req, reply) => {
9394
await req.pg.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['fail-opt-in'])
9495
await req.pg.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['fail-opt-in'])
95-
await req.pg.query('INSERT INTO nope(username) VALUES($1) RETURNING id', ['fail-opt-in'])
96+
// This one should fail (unknown_table does not exist) and trigger a rollback
97+
await req.pg.query('INSERT INTO unknown_table(username) VALUES($1) RETURNING id', ['fail-opt-in'])
98+
reply.send('complete')
99+
})
100+
101+
await fastify.inject({ url: '/fail' })
102+
103+
const response = await fastify.inject({
104+
method: 'GET',
105+
url: '/count-users'
106+
})
107+
108+
t.equal(extractUserCount(response), 0)
109+
})
110+
111+
t.test('Should trigger a rollback when failing to execute a query provided to a namespaced request pg decorator', async t => {
112+
const fastify = Fastify()
113+
t.teardown(() => fastify.close())
114+
115+
await fastify.register(fastifyPostgres, {
116+
connectionString,
117+
name: 'test'
118+
})
119+
120+
await fastify.pg.test.query('TRUNCATE users')
121+
122+
fastify.get('/count-users', async (req, reply) => {
123+
const result = await fastify.pg.test.query('SELECT COUNT(*) AS "userCount" FROM users WHERE username=\'fail-opt-in\'')
124+
125+
reply.send(result)
126+
})
127+
128+
fastify.get('/fail', { pg: { transact: true } }, async (req, reply) => {
129+
await req.pg.test.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['fail-opt-in'])
130+
await req.pg.test.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['fail-opt-in'])
131+
// This one should fail (unknown_table does not exist) and trigger a rollback
132+
await req.pg.test.query('INSERT INTO unknown_table(username) VALUES($1) RETURNING id', ['fail-opt-in'])
96133
reply.send('complete')
97134
})
98135

@@ -109,8 +146,8 @@ test('fastify postgress useTransaction route option', t => {
109146
t.end()
110147
})
111148

112-
test('combinations of registrationOptions.name and routeOptions.pg.transact that should not add hooks', t => {
113-
test('transact not set', t => {
149+
test('Should not add hooks with combinations of registration `options.name` and route options `pg.transact`', t => {
150+
t.test('Should not add hooks when `transact` is not set', t => {
114151
t.plan(1)
115152

116153
const fastify = Fastify()
@@ -126,7 +163,8 @@ test('combinations of registrationOptions.name and routeOptions.pg.transact that
126163

127164
fastify.inject({ url: '/' })
128165
})
129-
test('name set and transact not set', t => {
166+
167+
t.test('Should not add hooks when `name` is set and `transact` is not set', t => {
130168
t.plan(1)
131169

132170
const fastify = Fastify()
@@ -143,7 +181,8 @@ test('combinations of registrationOptions.name and routeOptions.pg.transact that
143181

144182
fastify.inject({ url: '/' })
145183
})
146-
test('name set and transact set to true', t => {
184+
185+
t.test('Should not add hooks when `name` is set and `transact` is set to `true`', t => {
147186
t.plan(1)
148187

149188
const fastify = Fastify()
@@ -160,7 +199,8 @@ test('combinations of registrationOptions.name and routeOptions.pg.transact that
160199

161200
fastify.inject({ url: '/' })
162201
})
163-
test('name not set and transact set to string', t => {
202+
203+
t.test('Should not add hooks when `name` is not set and `transact` is set and is a string', t => {
164204
t.plan(1)
165205

166206
const fastify = Fastify()
@@ -176,7 +216,8 @@ test('combinations of registrationOptions.name and routeOptions.pg.transact that
176216

177217
fastify.inject({ url: '/' })
178218
})
179-
test('name and transact set to different strings', t => {
219+
220+
t.test('Should not add hooks when `name` and `transact` are set to different strings', t => {
180221
t.plan(1)
181222

182223
const fastify = Fastify()
@@ -193,11 +234,12 @@ test('combinations of registrationOptions.name and routeOptions.pg.transact that
193234

194235
fastify.inject({ url: '/' })
195236
})
237+
196238
t.end()
197239
})
198240

199-
test('incorrect combinations of registrationOptions.name and routeOptions.pg.transact should throw errors', t => {
200-
t.test('name set as reserved keyword', t => {
241+
test('Should throw errors with incorrect combinations of registration `options.name` and route options `pg.transact`', t => {
242+
t.test('Should throw an error when `name` is set as reserved keyword', t => {
201243
t.plan(2)
202244

203245
const fastify = Fastify()
@@ -222,7 +264,7 @@ test('incorrect combinations of registrationOptions.name and routeOptions.pg.tra
222264
})
223265
})
224266

225-
t.test('named pg client has already registered', t => {
267+
t.test('Should throw an error when pg client has already been registered with the same name', t => {
226268
t.plan(2)
227269

228270
const fastify = Fastify()
@@ -249,7 +291,7 @@ test('incorrect combinations of registrationOptions.name and routeOptions.pg.tra
249291
})
250292
})
251293

252-
t.test('pg client has already registered', t => {
294+
t.test('Should throw an error when pg client has already been registered', t => {
253295
t.plan(2)
254296

255297
const fastify = Fastify()
@@ -272,5 +314,6 @@ test('incorrect combinations of registrationOptions.name and routeOptions.pg.tra
272314
})
273315
})
274316
})
317+
275318
t.end()
276319
})

0 commit comments

Comments
 (0)