Skip to content

Commit

Permalink
candishared: add method to set multiple context on event context
Browse files Browse the repository at this point in the history
  • Loading branch information
harissudrajat committed Dec 24, 2023
1 parent 96726bc commit 9d36628
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
9 changes: 9 additions & 0 deletions candishared/event_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ func (e *EventContext) SetContext(ctx context.Context) {
e.ctx = ctx
}

// SetContextWithValue set context with allow to multiple value
// If parent context is null will assign with context.Background() as default value
func (e *EventContext) SetContextWithValue(key, value any) {
if e.ctx == nil {
e.ctx = context.Background()
}
e.ctx = context.WithValue(e.ctx, key, value)
}

// SetWorkerType setter
func (e *EventContext) SetWorkerType(w string) {
e.workerType = w
Expand Down
29 changes: 29 additions & 0 deletions candishared/event_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package candishared

import (
"context"
"github.com/stretchr/testify/assert"
"testing"
)

func TestNewEventContext(t *testing.T) {
event := &EventContext{}

ctx := context.Background()
event.SetContext(context.WithValue(ctx, "key1", "value 1"))
event.SetContext(context.WithValue(ctx, "key2", "value 2"))

assert.Equal(t, nil, event.Context().Value("key1"))
assert.Equal(t, "value 2", event.Context().Value("key2"))
}

func TestMultiContext(t *testing.T) {
event := &EventContext{}
event.SetContext(context.Background())

event.SetContextWithValue("key1", "value 1")
event.SetContextWithValue("key2", "value 2")

assert.Equal(t, "value 1", event.Context().Value("key1"))
assert.Equal(t, "value 2", event.Context().Value("key2"))
}

0 comments on commit 9d36628

Please sign in to comment.