Open
Description
Description
Default ContextOperator
uses genetic type any
(v0.2.3) (comparable
#88 ) as key for storing/getting Tx
.
Changing the key
field to the function that return (calculate) the key, will make ContextOperator
more flexible.
// ContextOperator inject and extract Tx from context.Context.
type ContextOperator[B comparable, T Tx] struct {
key func() B
}
// NewContextOperator returns new ContextOperator.
func NewContextOperator[B comparable, T Tx](key func() B) *ContextOperator[B, T] {
return &ContextOperator[B, T]{
key: key,
}
}
// Inject returns new context.Context contains Tx as value.
func (p *ContextOperator[B, T]) Inject(ctx context.Context, tx T) context.Context {
return context.WithValue(ctx, p.key(), tx)
}
// Extract returns Tx extracted from context.Context.
func (p *ContextOperator[B, T]) Extract(ctx context.Context) (T, bool) {
c, ok := ctx.Value(p.key()).(T)
return c, ok
}