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

ContextOperator.Inject: key is not comparable #88

Closed
kozmod opened this issue Jan 22, 2024 · 0 comments · Fixed by #89
Closed

ContextOperator.Inject: key is not comparable #88

kozmod opened this issue Jan 22, 2024 · 0 comments · Fixed by #89
Assignees
Labels
bug Something isn't working enhancement New feature or request

Comments

@kozmod
Copy link
Owner

kozmod commented Jan 22, 2024

Description

BUG:
default ContextOperator use database (TxBeginner) for extracting and injecting ( Inject/Extract) transaction (Tx) to context.Context:

// ContextOperator inject and extract Tx from context.Context.
type ContextOperator[B any 👈🏻 , T Tx] struct {
	beginner *B
}

// NewContextOperator returns new ContextOperator.
func NewContextOperator[B any, T Tx](b *B) *ContextOperator[B, T] {
	return &ContextOperator[B, T]{
		beginner: b,
	}
}

// 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.beginner, tx) 👈🏻
}

// Extract returns Tx extracted from context.Context.
func (p *ContextOperator[B, T]) Extract(ctx context.Context) (T, bool) {
	c, ok := ctx.Value(p.beginner).(T) 👈🏻
	return c, ok
}

if type B is not comparable, context.Context produce the panic: " key is not comparable"

To avoid the produce, need to change type B to comparable:

// ContextOperator inject and extract Tx from context.Context.
type ContextOperator[B comparable, T Tx] struct {
	beginner B
}

// NewContextOperator returns new ContextOperator.
func NewContextOperator[B comparable, T Tx](b B) *ContextOperator[B, T] {
	return &ContextOperator[B, T]{
		beginner: b,
	}
}

ENCHANCEMENT:
default ContextOperator use *B type in the constructor. It's a bit unhandy.

// NewContextOperator returns new ContextOperator.
func NewContextOperator[B any, T Tx](b *B 👈🏻) *ContextOperator[B, T] {
	return &ContextOperator[B, T]{
		beginner: b,
	}
}

the pointer may be removed.

@kozmod kozmod added bug Something isn't working enhancement New feature or request labels Jan 22, 2024
@kozmod kozmod self-assigned this Jan 22, 2024
kozmod added a commit that referenced this issue Jan 23, 2024
…rable

[#88] fix default `ContextOperator`: change `B` to comparable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant