Skip to content

Commit

Permalink
fix: added additional time support and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed Jan 27, 2022
1 parent 2339c6a commit 1123800
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
19 changes: 15 additions & 4 deletions common/coral/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package coral

import (
"encoding/json"
"reflect"
"time"

"github.com/pkg/errors"
Expand Down Expand Up @@ -33,14 +34,24 @@ func (t *Time) UnmarshalJSON(data []byte) error {
date, ok := v["$date"].(string)
if !ok || date == "" {
// Try to handle the case where we get something that looks like
// this: {"$date":{"$numberLong":"-62075098782000"}}
if _, ok := v["$date"].(map[string]int64); ok {
logrus.Warn("saw a date in the format: { $date: { $numberLong: -000 } }")
// this: {"$date":-62075098782000}
if _, ok := v["$date"].(map[string]float64); ok {
logrus.Warn("saw a date in the format: { $date: -62075098782000 }")

return nil
}

return errors.Errorf("invalid format: %#v", v)
// Try to handle the case where we get something that looks like
// this: {"$date":{"$numberLong":"-62075098782000"}}
if obj, ok := v["$date"].(map[string]interface{}); ok {
if _, ok := obj["$numberLong"].(string); ok {
logrus.Warn("saw a date in the format: { $date: { $numberLong: \"-62075098782000\" } }")

return nil
}
}

return errors.Errorf("invalid format: %#v, %s", v["$date"], reflect.TypeOf(v["$date"]))
}

tt, err := time.Parse(time.RFC3339, date)
Expand Down
26 changes: 26 additions & 0 deletions common/coral/time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package coral_test

import (
"coral-importer/common/coral"
"testing"
)

func TestTimeUnmarshalJSON(t *testing.T) {
var tm coral.Time

inputs := []struct {
name string
value string
}{
{name: "normal date time", value: `{ "$date": "2018-10-25T23:57:49.053Z" }`},
{name: "negative number long", value: `{ "$date": { "$numberLong": "-62075098782000" } }`},
}

for _, input := range inputs {
t.Run(input.name, func(t *testing.T) {
if err := tm.UnmarshalJSON([]byte(input.value)); err != nil {
t.Errorf("expected no error with input %s, got %v", input.value, err)
}
})
}
}

0 comments on commit 1123800

Please sign in to comment.