Skip to content

Commit 359307e

Browse files
authored
fix: Month JSON unmarshaling now enforcing year and month only (#906)
1 parent 7c5fa15 commit 359307e

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

internal/types/month.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,17 @@ func (m Month) MarshalJSON() ([]byte, error) {
2929

3030
// UnmarshalJSON implements the json.Unmarshaler interface.
3131
// The month is expected to be a string in a format accepted by ParseDate.
32+
// From the parsed string, everything is then ignored except the year and month
3233
func (m *Month) UnmarshalJSON(data []byte) error {
33-
return (*time.Time)(m).UnmarshalJSON(data)
34+
var date time.Time
35+
err := date.UnmarshalJSON(data)
36+
if err != nil {
37+
return err
38+
}
39+
40+
month := NewMonth(date.Year(), date.Month())
41+
*m = month
42+
return nil
3443
}
3544

3645
// MonthOf returns the Month in which a time occurs in that time's location.

internal/types/month_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package types_test
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
7+
"github.com/envelope-zero/backend/v3/internal/types"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestMonthUnmarshalJSON(t *testing.T) {
12+
var target struct {
13+
Month types.Month
14+
}
15+
jsonString := []byte(`{ "month": "2024-05-12T17:59:23+02:00" }`)
16+
17+
err := json.Unmarshal(jsonString, &target)
18+
19+
assert.Nil(t, err)
20+
assert.Equal(t, types.NewMonth(2024, 5), target.Month)
21+
}

0 commit comments

Comments
 (0)