Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow other formats when unmarshalling time #1964

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
14 changes: 12 additions & 2 deletions graphql/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,18 @@ func MarshalTime(t time.Time) Marshaler {
}

func UnmarshalTime(v interface{}) (time.Time, error) {
formats := []string{
time.RFC3339Nano,
"2006-01-02 15:04:05.999999999",
"2006-01-02",
}
if tmpStr, ok := v.(string); ok {
return time.Parse(time.RFC3339Nano, tmpStr)
for _, f := range formats {
t, err := time.Parse(f, tmpStr)
if err == nil {
return t, nil
}
}
}
return time.Time{}, errors.New("time should be RFC3339Nano formatted string")
return time.Time{}, errors.New("time is not a string in a recognized format")
}
64 changes: 64 additions & 0 deletions graphql/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,67 @@ func TestTime(t *testing.T) {
require.True(t, initialTime.Equal(newTime), "expected times %v and %v to equal", initialTime, newTime)
})
}

func TestUnmarshalTime(t *testing.T) {
tests := []struct {
name string
in interface{}
want time.Time
wantErr bool
}{
{
name: "RFC3339Nano",
in: "2022-02-10T10:20:30.123456789Z",
want: time.Date(2022, 02, 10, 10, 20, 30, 123456789, time.UTC),
wantErr: false,
},
{
name: "RFC3339",
in: "2022-02-10T10:20:30Z",
want: time.Date(2022, 02, 10, 10, 20, 30, 0, time.UTC),
wantErr: false,
},
{
name: "UTC ISO with time",
in: "2022-02-10 10:20:30",
want: time.Date(2022, 02, 10, 10, 20, 30, 0, time.UTC),
wantErr: false,
},
{
name: "UTC ISO with time and nsec",
in: "2022-02-10 10:20:30.123456789",
want: time.Date(2022, 02, 10, 10, 20, 30, 123456789, time.UTC),
wantErr: false,
},
{
name: "UTC ISO date",
in: "2022-02-10",
want: time.Date(2022, 02, 10, 0, 0, 0, 0, time.UTC),
wantErr: false,
},
{
name: "Invalid format 1",
in: "20220210",
want: time.Time{},
wantErr: true,
},
{
name: "Invalid format 1",
in: "2022-02-33",
want: time.Time{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := UnmarshalTime(tt.in)
if (err != nil) != tt.wantErr {
t.Errorf("UnmarshalTime() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !got.Equal(tt.want) {
t.Errorf("UnmarshalTime() = %v, want %v", got, tt.want)
}
})
}
}