github.com/corylanou/buffalo@v0.8.0/middleware/pop_transaction.go (about)

     1  package middleware
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/gobuffalo/buffalo"
     7  	"github.com/markbates/pop"
     8  )
     9  
    10  // PopTransaction is a piece of Buffalo middleware that wraps each
    11  // request in a transaction that will automatically get committed or
    12  // rolledback. It will also add a field to the log, "db", that
    13  // shows the total duration spent during the request making database
    14  // calls.
    15  var PopTransaction = func(db *pop.Connection) buffalo.MiddlewareFunc {
    16  	return func(h buffalo.Handler) buffalo.Handler {
    17  		return func(c buffalo.Context) error {
    18  			// wrap all requests in a transaction and set the length
    19  			// of time doing things in the db to the log.
    20  			return db.Transaction(func(tx *pop.Connection) error {
    21  				start := tx.Elapsed
    22  				defer func() {
    23  					finished := tx.Elapsed
    24  					elapsed := time.Duration(finished - start)
    25  					c.LogField("db", elapsed)
    26  				}()
    27  				c.Set("tx", tx)
    28  				return h(c)
    29  			})
    30  		}
    31  	}
    32  }