Skip to content

Commit

Permalink
graphql.Time unmarshal unix nano time (#486)
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelnikolov authored Dec 21, 2021
1 parent 9379f9d commit 9d31459
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
8 changes: 7 additions & 1 deletion time.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,13 @@ func (t *Time) UnmarshalGraphQL(input interface{}) error {
t.Time = time.Unix(int64(input), 0)
return nil
case int64:
t.Time = time.Unix(input, 0)
if input >= 1e10 {
sec := input / 1e9
nsec := input - (sec * 1e9)
t.Time = time.Unix(sec, nsec)
} else {
t.Time = time.Unix(input, 0)
}
return nil
case float64:
t.Time = time.Unix(int64(input), 0)
Expand Down
26 changes: 16 additions & 10 deletions time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestTime_ImplementsUnmarshaler(t *testing.T) {
}

func TestTime_ImplementsGraphQLType(t *testing.T) {
gt := new(Time)
gt := &Time{}

if gt.ImplementsGraphQLType("foobar") {
t.Error("Type *Time must not claim to implement GraphQL type 'foobar'")
Expand All @@ -36,7 +36,7 @@ func TestTime_ImplementsGraphQLType(t *testing.T) {
func TestTime_MarshalJSON(t *testing.T) {
var err error
var b1, b2 []byte
ref := time.Date(2021, time.April, 20, 12, 3, 23, 0, time.UTC)
ref := time.Date(2021, time.April, 20, 12, 3, 23, 551476231, time.UTC)

if b1, err = json.Marshal(ref); err != nil {
t.Error(err)
Expand All @@ -57,8 +57,8 @@ func TestTime_UnmarshalGraphQL(t *testing.T) {
type args struct {
input interface{}
}

ref := time.Date(2021, time.April, 20, 12, 3, 23, 0, time.UTC)
ref := time.Date(2021, time.April, 20, 12, 3, 23, 551476231, time.UTC)
refZeroNano := time.Unix(ref.Unix(), 0)

t.Run("invalid", func(t *testing.T) {
tests := []struct {
Expand Down Expand Up @@ -111,46 +111,52 @@ func TestTime_UnmarshalGraphQL(t *testing.T) {
args: args{
input: ref.Format(time.RFC3339),
},
wantEq: ref,
wantEq: refZeroNano,
},
{
name: "bytes",
args: args{
input: []byte(ref.Format(time.RFC3339)),
},
wantEq: ref,
wantEq: refZeroNano,
},
{
name: "int32",
args: args{
input: int32(ref.Unix()),
},
wantEq: ref,
wantEq: refZeroNano,
},
{
name: "int64",
args: args{
input: ref.Unix(),
},
wantEq: refZeroNano,
},
{
name: "int64-nano",
args: args{
input: ref.UnixNano(),
},
wantEq: ref,
},
{
name: "float64",
args: args{
input: float64(ref.Unix()),
},
wantEq: ref,
wantEq: refZeroNano,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gt := new(Time)
gt := &Time{}
if err := gt.UnmarshalGraphQL(tt.args.input); err != nil {
t.Errorf("UnmarshalGraphQL() error = %v", err)
return
}

if !gt.Equal(tt.wantEq) {
t.Errorf("UnmarshalGraphQL() got = %v, want = %v", gt, tt.wantEq)
}
Expand Down

0 comments on commit 9d31459

Please sign in to comment.