Skip to content

Commit

Permalink
fix: marshaling of WithSubject events
Browse files Browse the repository at this point in the history
If a struct is composed with an interface the go json marshaler
treats that as a field, thus we need to have a custom json marshaler
for the type.
  • Loading branch information
turip committed Aug 7, 2024
1 parent f680c38 commit 5419b3c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions openmeter/watermill/marshaler/source.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package marshaler

import (
"encoding/json"
"errors"

"github.com/openmeterio/openmeter/internal/event/metadata"
Expand Down Expand Up @@ -42,3 +43,9 @@ func (e *eventWithSource) Validate() error {
func (e *eventWithSource) EventName() string {
return e.Event.EventName()
}

// MarshalJSON marshals the event only, as JSON library embeds the Event name into the output,
// if the composed object is a pointer to an interface. (e.g. we would get "Event": {} in the payload)
func (e *eventWithSource) MarshalJSON() ([]byte, error) {
return json.Marshal(e.Event)
}
47 changes: 47 additions & 0 deletions openmeter/watermill/marshaler/source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package marshaler

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/openmeterio/openmeter/internal/event/metadata"
)

type event struct {
Value string `json:"value"`
}

func (e *event) EventMetadata() metadata.EventMetadata {
return metadata.EventMetadata{}
}

func (e *event) Validate() error {
return nil
}

func (e *event) EventName() string {
return "event"
}

func TestWithSubject(t *testing.T) {
marshaler := New(nil)

ev := &event{
Value: "value",
}

evWithSource := WithSource("source", ev)
msg, err := marshaler.Marshal(evWithSource)

// Check if the source is set in the metadata
assert.NoError(t, err)
assert.Equal(t, "source", msg.Metadata.Get(CloudEventsHeaderSource))

// Check if the event can be unmarshaled
unmarshaledEvent := &event{}
err = marshaler.Unmarshal(msg, unmarshaledEvent)
assert.NoError(t, err)

assert.Equal(t, ev, unmarshaledEvent)
}

0 comments on commit 5419b3c

Please sign in to comment.