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