Skip to content
This repository has been archived by the owner on Jan 2, 2024. It is now read-only.

Commit

Permalink
apitypes: omit PhaseResponse.End from JSON if empty (#274)
Browse files Browse the repository at this point in the history
  • Loading branch information
bmizerany committed Mar 3, 2023
1 parent f26506a commit 4753d71
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
21 changes: 21 additions & 0 deletions api/apitypes/apitypes.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package apitypes

import (
"encoding/json"
"fmt"
"time"

Expand Down Expand Up @@ -34,6 +35,26 @@ type PhaseResponse struct {
Trial bool `json:"trial,omitempty"`
}

func (pr PhaseResponse) MarshalJSON() ([]byte, error) {
type Alias PhaseResponse
if pr.End.IsZero() {
return json.Marshal(&struct {
*Alias
End byte `json:"end,omitempty"`
}{
Alias: (*Alias)(&pr),
})
} else {
return json.Marshal(&struct {
*Alias
End time.Time `json:"end"`
}{
Alias: (*Alias)(&pr),
End: pr.End,
})
}
}

type PaymentMethodsResponse struct {
Org string `json:"org"`
PaymentMethods []payment.Method `json:"methods"`
Expand Down
38 changes: 38 additions & 0 deletions api/apitypes/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package apitypes

import (
"encoding/json"
"testing"
"time"
)

func TestPhaseResponseJSON(t *testing.T) {
cases := []struct {
pr PhaseResponse
want string
}{
{
pr: PhaseResponse{},
want: `{"effective":"0001-01-01T00:00:00Z"}`,
},
{
pr: PhaseResponse{
End: time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC),
},
want: `{"effective":"0001-01-01T00:00:00Z","end":"2018-01-01T00:00:00Z"}`,
},
}

for _, tt := range cases {
t.Run("", func(t *testing.T) {
data, err := json.Marshal(tt.pr)
if err != nil {
t.Fatal(err)
}
got := string(data)
if got != tt.want {
t.Errorf("got = %q, want %q", got, tt.want)
}
})
}
}

0 comments on commit 4753d71

Please sign in to comment.