github.com/orderbynull/buffalo@v0.11.1/middleware/pop_transaction.go (about)

     1  package middleware
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/pkg/errors"
     7  
     8  	"github.com/gobuffalo/buffalo"
     9  	"github.com/gobuffalo/pop"
    10  )
    11  
    12  // PopTransaction is a piece of Buffalo middleware that wraps each
    13  // request in a transaction that will automatically get committed or
    14  // rolledback. It will also add a field to the log, "db", that
    15  // shows the total duration spent during the request making database
    16  // calls.
    17  var PopTransaction = func(db *pop.Connection) buffalo.MiddlewareFunc {
    18  	return func(h buffalo.Handler) buffalo.Handler {
    19  		return func(c buffalo.Context) error {
    20  			// wrap all requests in a transaction and set the length
    21  			// of time doing things in the db to the log.
    22  			err := db.Transaction(func(tx *pop.Connection) error {
    23  				start := tx.Elapsed
    24  				defer func() {
    25  					finished := tx.Elapsed
    26  					elapsed := time.Duration(finished - start)
    27  					c.LogField("db", elapsed)
    28  				}()
    29  				c.Set("tx", tx)
    30  				if err := h(c); err != nil {
    31  					return err
    32  				}
    33  				if res, ok := c.Response().(*buffalo.Response); ok {
    34  					if res.Status < 200 || res.Status >= 400 {
    35  						return errNonSuccess
    36  					}
    37  				}
    38  				return nil
    39  			})
    40  			if err != nil && errors.Cause(err) != errNonSuccess {
    41  				return err
    42  			}
    43  			return nil
    44  		}
    45  	}
    46  }
    47  
    48  var errNonSuccess = errors.New("non success status code")