From f00cefc4690a0fe3f5c274b28ae9c55d66b1ae66 Mon Sep 17 00:00:00 2001 From: Luca Rainone Date: Sun, 22 Oct 2023 07:42:28 +0200 Subject: [PATCH 1/2] 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 * refactor: avoiding empty return statement --------- Co-authored-by: Luca Rainone Co-authored-by: Manuel Spigolon --- index.js | 12 +++++++----- test/req-initialization.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) 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/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() }) From 2e6cb746092fd90b8d27e047cec9e393c6421098 Mon Sep 17 00:00:00 2001 From: Manuel Spigolon Date: Sun, 22 Oct 2023 07:45:11 +0200 Subject: [PATCH 2/2] Bumped v5.2.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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",