Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down Expand Up @@ -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) => {
Expand Down
34 changes: 34 additions & 0 deletions test/req-initialization.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
Loading