Skip to content

Automatic transactions #75

@mcollina

Description

@mcollina

🚀 Feature Proposal

In most applications I've seen:

fastify.get('/something', function (req, reply) {
  return this.pg.transact(async (client) => {
      const { rows } = await client.query('SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id])
      return rows
  })
})

I think we could greatly simplify this by having some dedicated syntax to avoid developer errors

3rd argument

fastify.get('/something', { pg: { transact: true } }, function (req, reply, client) {
  const { rows } = await client.query('SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id])
  return rows
})

or even better

fastify.register(require('fastify-postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres',
  wrapRoutesWithTransaction: true
})

fastify.get('/something', function (req, reply, client) {
  const { rows } = await client.query('SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id])
  return rows
})

This can be implemented by having an 'onRoute' hook that wraps the handler.

Decorator

fastify.get('/something', { pg: { transact: true } }, function (req, reply) {
  const { rows } = await req.pg.query('SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id])
  return rows
})

or even better

fastify.register(require('fastify-postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres',
  wrapRoutesWithTransaction: true
})

fastify.get('/something', function (req, reply) {
  const { rows } = await req.pg.query('SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id])
  return rows
})

This can be implemented by having a 'preHandler' hook that starts the transaction and an 'onSend' hook that commits or roll back it.


What do you prefer? The decorator is probably the more idiomatic approach, even it it will require a bit more work to implement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions