Skip to content

Commit f00cefc

Browse files
LucaRainoneLuca RainoneEomm
authored
fix: referenceError on schema validation failure. (#164)
* fix: check the initialization of the client in onSend handler preventing referenceError on schema validation failure. * remove unused and useless code Co-authored-by: Manuel Spigolon <[email protected]> * refactor: avoiding empty return statement --------- Co-authored-by: Luca Rainone <[email protected]> Co-authored-by: Manuel Spigolon <[email protected]>
1 parent b47f841 commit f00cefc

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

index.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -171,12 +171,14 @@ function fastifyPostgres (fastify, options, next) {
171171

172172
const onSend = async (req) => {
173173
const requestClient = extractRequestClient(req, transact)
174-
try {
175-
if (!req[transactionFailedSymbol]) {
176-
await requestClient.query('COMMIT')
174+
if (requestClient) {
175+
try {
176+
if (!req[transactionFailedSymbol]) {
177+
await requestClient.query('COMMIT')
178+
}
179+
} finally {
180+
requestClient.release()
177181
}
178-
} finally {
179-
requestClient.release()
180182
}
181183
}
182184

test/req-initialization.test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,38 @@ test('When we use the fastify-postgres transaction route option', t => {
143143
t.equal(extractUserCount(response), 0)
144144
})
145145

146+
t.test('Should work properly with `schema` option and validation failure', async t => {
147+
const fastify = Fastify()
148+
t.teardown(() => fastify.close())
149+
150+
await fastify.register(fastifyPostgres, {
151+
connectionString
152+
})
153+
154+
fastify.post('/schema-validation', {
155+
schema: {
156+
body: {
157+
type: 'object',
158+
properties: {
159+
hello: { type: 'string' }
160+
},
161+
required: ['hello']
162+
}
163+
},
164+
pg: { transact: true }
165+
}, async (req, reply) => {
166+
t.fail('should never execute the handler')
167+
})
168+
169+
const response = await fastify.inject({
170+
url: '/schema-validation',
171+
method: 'POST',
172+
body: { notValid: 'json input' }
173+
})
174+
t.not(response.body, 'never success')
175+
t.equal(response.json().code, 'FST_ERR_VALIDATION')
176+
})
177+
146178
t.end()
147179
})
148180

0 commit comments

Comments
 (0)