-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransaction.go
More file actions
38 lines (29 loc) · 890 Bytes
/
transaction.go
File metadata and controls
38 lines (29 loc) · 890 Bytes
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
package authorizer
import (
"context"
"gorm.io/gorm"
)
type TransactionContextKey string
const (
TransactionCtx = TransactionContextKey("DB_TRANSACTION")
)
type TransactionFetcher interface {
IsTransactionCtx(ctx context.Context) bool
GetTransactionCtx(ctx context.Context) *gorm.DB
WithTransactionCtx(ctx context.Context, tx *gorm.DB) context.Context
}
type SimpleTransactionFetcher struct{}
func (s SimpleTransactionFetcher) GetTransactionCtx(ctx context.Context) *gorm.DB {
if v := ctx.Value(TransactionCtx); v != nil {
if dbTx, ok := v.(*gorm.DB); ok {
return dbTx
}
}
return nil
}
func (s SimpleTransactionFetcher) WithTransactionCtx(ctx context.Context, tx *gorm.DB) context.Context {
return context.WithValue(ctx, TransactionCtx, tx)
}
func (s SimpleTransactionFetcher) IsTransactionCtx(ctx context.Context) bool {
return s.GetTransactionCtx(ctx) != nil
}