Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change key accessing for default ContextOperator #90

Open
kozmod opened this issue Jan 23, 2024 · 0 comments
Open

Change key accessing for default ContextOperator #90

kozmod opened this issue Jan 23, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed hold Extra discussion is needed

Comments

@kozmod
Copy link
Owner

kozmod commented Jan 23, 2024

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
}
@kozmod kozmod added enhancement New feature or request help wanted Extra attention is needed labels Jan 23, 2024
@kozmod kozmod self-assigned this Jan 23, 2024
@kozmod kozmod added good first issue Good for newcomers hold Extra discussion is needed labels Jan 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed hold Extra discussion is needed
Projects
None yet
Development

No branches or pull requests

1 participant