Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion enriched_activities.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package stream
import (
"encoding/json"
"errors"
"reflect"
"strings"

"github.com/fatih/structs"
)
Expand Down Expand Up @@ -74,7 +76,20 @@ func (a *EnrichedActivity) UnmarshalJSON(b []byte) error {
// MarshalJSON encodes the EnrichedActivity to a valid JSON bytes slice. It's required because of
// the custom JSON fields and time formats.
func (a EnrichedActivity) MarshalJSON() ([]byte, error) {
data := structs.New(a).Map()
fields := structs.New(a).Fields()
data := make(map[string]interface{}, len(fields))
for _, f := range fields {
if f.Kind() == reflect.Struct {
tag := f.Tag("json")
if !strings.HasSuffix(tag, ",omitempty") || !structs.IsZero(f.Value()) {
data[strings.TrimSuffix(tag, ",omitempty")] = f.Value()
}
}
}
for k, v := range a.Extra {
data[k] = v
}

for k, v := range a.Extra {
data[k] = v
}
Expand Down
13 changes: 13 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,19 @@ func (a *Data) decode(data map[string]interface{}) error {
return nil
}

// MarshalJSON encodes data into json.
func (a Data) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{}, len(a.Extra))
for k, v := range a.Extra {
m[k] = v
}
result := map[string]interface{}{
"id": a.ID,
"data": m,
}
return json.Marshal(result)
}

// Rate is the information to be filled if a rate limited response
type Rate struct {
// Limit is the existing limit for the resource
Expand Down
13 changes: 13 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,16 @@ func TestTimeMarshalUnmarshalJSON(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, st, out)
}

func TestEnrichedActivityMarshal(t *testing.T) {
e := stream.EnrichedActivity{
Actor: stream.Data{
ID: "my_id",
Extra: map[string]interface{}{"a": 1, "b": "c"},
},
}

b, err := json.Marshal(e)
require.NoError(t, err)
require.JSONEq(t, `{"actor": {"id":"my_id","data":{"a":1,"b":"c"}}}`, string(b))
}