Skip to content

Commit

Permalink
fix: Month JSON unmarshaling now enforcing year and month only (#906)
Browse files Browse the repository at this point in the history
  • Loading branch information
morremeyer authored Dec 27, 2023
1 parent 7c5fa15 commit 359307e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
11 changes: 10 additions & 1 deletion internal/types/month.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,17 @@ func (m Month) MarshalJSON() ([]byte, error) {

// UnmarshalJSON implements the json.Unmarshaler interface.
// The month is expected to be a string in a format accepted by ParseDate.
// From the parsed string, everything is then ignored except the year and month
func (m *Month) UnmarshalJSON(data []byte) error {
return (*time.Time)(m).UnmarshalJSON(data)
var date time.Time
err := date.UnmarshalJSON(data)
if err != nil {
return err
}

month := NewMonth(date.Year(), date.Month())
*m = month
return nil
}

// MonthOf returns the Month in which a time occurs in that time's location.
Expand Down
21 changes: 21 additions & 0 deletions internal/types/month_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package types_test

import (
"encoding/json"
"testing"

"github.com/envelope-zero/backend/v3/internal/types"
"github.com/stretchr/testify/assert"
)

func TestMonthUnmarshalJSON(t *testing.T) {
var target struct {
Month types.Month
}
jsonString := []byte(`{ "month": "2024-05-12T17:59:23+02:00" }`)

err := json.Unmarshal(jsonString, &target)

assert.Nil(t, err)
assert.Equal(t, types.NewMonth(2024, 5), target.Month)
}

0 comments on commit 359307e

Please sign in to comment.