Skip to content

Commit

Permalink
fix: do not produce null fields in marshalled json
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Aug 25, 2023
1 parent bdd7f87 commit 07479ef
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
4 changes: 2 additions & 2 deletions routing/http/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,11 @@ func TestProviders(t *testing.T) {
}

t.Run("JSON Response", func(t *testing.T) {
runTest(t, mediaTypeJSON, false, `{"Providers":[{"Addrs":[],"ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vn","Protocols":["transport-bitswap"],"Schema":"peer"},{"Schema":"bitswap","Protocol":"transport-bitswap","ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vz","Addrs":[]}]}`)
runTest(t, mediaTypeJSON, false, `{"Providers":[{"Addrs":[],"ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vn","Protocols":["transport-bitswap"],"Schema":"peer"},{"Schema":"bitswap","Protocol":"transport-bitswap","ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vz"}]}`)
})

t.Run("NDJSON Response", func(t *testing.T) {
runTest(t, mediaTypeNDJSON, true, `{"Addrs":[],"ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vn","Protocols":["transport-bitswap"],"Schema":"peer"}`+"\n"+`{"Schema":"bitswap","Protocol":"transport-bitswap","ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vz","Addrs":[]}`+"\n")
runTest(t, mediaTypeNDJSON, true, `{"Addrs":[],"ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vn","Protocols":["transport-bitswap"],"Schema":"peer"}`+"\n"+`{"Schema":"bitswap","Protocol":"transport-bitswap","ID":"12D3KooWM8sovaEGU1bmiWGWAzvs47DEcXKZZTuJnpQyVTkRs2Vz"}`+"\n")
})
}

Expand Down
2 changes: 1 addition & 1 deletion routing/http/types/record_bitswap.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ type BitswapRecord struct {
Schema string
Protocol string
ID *peer.ID
Addrs []Multiaddr
Addrs []Multiaddr `json:",omitempty"`
}

func (br *BitswapRecord) GetSchema() string {
Expand Down
13 changes: 11 additions & 2 deletions routing/http/types/record_peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,18 @@ func (pr PeerRecord) MarshalJSON() ([]byte, error) {
m[key] = val
}

Check warning on line 65 in routing/http/types/record_peer.go

View check run for this annotation

Codecov / codecov/patch

routing/http/types/record_peer.go#L64-L65

Added lines #L64 - L65 were not covered by tests
}

// Schema and ID must always be set.
m["Schema"] = pr.Schema
m["ID"] = pr.ID
m["Addrs"] = pr.Addrs
m["Protocols"] = pr.Protocols

if pr.Addrs != nil {
m["Addrs"] = pr.Addrs
}

if pr.Protocols != nil {
m["Protocols"] = pr.Protocols
}

return drjson.MarshalJSONBytes(m)
}

0 comments on commit 07479ef

Please sign in to comment.