diff --git a/index.js b/index.js index 7c0577d..869a303 100644 --- a/index.js +++ b/index.js @@ -61,6 +61,10 @@ function extractRequestClient (req, transact) { return req.pg } + if (!req.pg) { + return null + } + const requestClient = req.pg[transact] if (!requestClient) { throw new Error(`request client '${transact}' does not exist`) @@ -166,7 +170,11 @@ function fastifyPostgres (fastify, options, next) { const onError = (req, _reply, _error, done) => { req[transactionFailedSymbol] = true - extractRequestClient(req, transact).query('ROLLBACK', done) + const requestClient = extractRequestClient(req, transact) + if (!requestClient) { + return done() + } + requestClient.query('ROLLBACK', done) } const onSend = async (req) => { diff --git a/test/req-initialization.test.js b/test/req-initialization.test.js index 6f71d40..236caae 100644 --- a/test/req-initialization.test.js +++ b/test/req-initialization.test.js @@ -174,6 +174,40 @@ test('When we use the fastify-postgres transaction route option', async t => { t.assert.notStrictEqual(response.body, 'never success') t.assert.strictEqual(response.json().code, 'FST_ERR_VALIDATION') }) + + await t.test('Should work properly with `schema` option and validation failure on a namespaced request pg decorator', async t => { + const fastify = Fastify() + t.after(() => fastify.close()) + + await fastify.register(fastifyPostgres, { + connectionString, + name: 'test' + }) + + fastify.post('/schema-validation', { + schema: { + body: { + type: 'object', + properties: { + hello: { type: 'string' } + }, + required: ['hello'] + } + }, + pg: { transact: 'test' } + }, async () => { + t.assert.fail('should never execute the handler') + }) + + const response = await fastify.inject({ + url: '/schema-validation', + method: 'POST', + body: { notValid: 'json input' } + }) + t.assert.strictEqual(response.statusCode, 400) + t.assert.strictEqual(response.json().code, 'FST_ERR_VALIDATION') + t.assert.strictEqual(response.json().message, "body must have required property 'hello'") + }) }) test('Should not add hooks with combinations of registration `options.name` and route options `pg.transact`', async t => {