diff --git a/index.js b/index.js index 1c5162f..429fe85 100644 --- a/index.js +++ b/index.js @@ -171,12 +171,14 @@ function fastifyPostgres (fastify, options, next) { const onSend = async (req) => { const requestClient = extractRequestClient(req, transact) - try { - if (!req[transactionFailedSymbol]) { - await requestClient.query('COMMIT') + if (requestClient) { + try { + if (!req[transactionFailedSymbol]) { + await requestClient.query('COMMIT') + } + } finally { + requestClient.release() } - } finally { - requestClient.release() } } diff --git a/package.json b/package.json index 3be7ef9..437f54f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "5.2.1", + "version": "5.2.2", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "types": "index.d.ts", diff --git a/test/req-initialization.test.js b/test/req-initialization.test.js index 5a11b6f..acacc14 100644 --- a/test/req-initialization.test.js +++ b/test/req-initialization.test.js @@ -143,6 +143,38 @@ test('When we use the fastify-postgres transaction route option', t => { t.equal(extractUserCount(response), 0) }) + t.test('Should work properly with `schema` option and validation failure', async t => { + const fastify = Fastify() + t.teardown(() => fastify.close()) + + await fastify.register(fastifyPostgres, { + connectionString + }) + + fastify.post('/schema-validation', { + schema: { + body: { + type: 'object', + properties: { + hello: { type: 'string' } + }, + required: ['hello'] + } + }, + pg: { transact: true } + }, async (req, reply) => { + t.fail('should never execute the handler') + }) + + const response = await fastify.inject({ + url: '/schema-validation', + method: 'POST', + body: { notValid: 'json input' } + }) + t.not(response.body, 'never success') + t.equal(response.json().code, 'FST_ERR_VALIDATION') + }) + t.end() })