Skip to content

Commit

Permalink
Add custom parsing to aggregation results to support time since epoch
Browse files Browse the repository at this point in the history
  • Loading branch information
dimroc committed Jul 9, 2016
1 parent 88523f9 commit f130e30
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions cityservice/citylib/city.go
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
elastigo "github.com/dimroc/elastigo/lib"
. "github.com/dimroc/urbanevents/cityservice/utils"
"strconv"
"strings"
"time"
)
Expand Down Expand Up @@ -174,19 +175,19 @@ type aggregationResult struct {
DocCount int64 `json:"doc_count"`
Range struct {
Buckets []struct {
Key string `json:"key"`
DocCount int `json:"doc_count"`
To time.Time `json:"to_as_string"`
Key string `json:"key"`
DocCount int `json:"doc_count"`
To safeParseTime `json:"to_as_string"`
} `json:"buckets"`
} `json:"range"`
} `json:"twitter"`
Instagram struct {
DocCount int64 `json:"doc_count"`
Range struct {
Buckets []struct {
Key string `json:"key"`
DocCount int `json:"doc_count"`
To time.Time `json:"to_as_string"`
Key string `json:"key"`
DocCount int `json:"doc_count"`
To safeParseTime `json:"to_as_string"`
} `json:"buckets"`
} `json:"range"`
} `json:"instagram"`
Expand All @@ -203,7 +204,7 @@ func (a *aggregationResult) GetCountsAndDays() ([]int, []int, []time.Time) {
for index, bucket := range buckets {
// Reverse order of tweets and days so it's descending
tweets[length-1-index] = bucket.DocCount
days[length-1-index] = bucket.To
days[length-1-index] = bucket.To.Time
}

buckets = a.Counts.Instagram.Range.Buckets
Expand All @@ -216,3 +217,24 @@ func (a *aggregationResult) GetCountsAndDays() ([]int, []int, []time.Time) {

return tweets, instagrams, days
}

type safeParseTime struct {
time.Time
}

func (spt *safeParseTime) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b[:]), "\"")

t, e1 := time.Parse(time.RFC3339, s) // Try default RFC3339
if e1 == nil {
spt.Time = t
} else {
// We slice off the first 10 characters to assume
// int is milliseconds since Epoch
i, err := strconv.ParseInt(s[:10], 10, 64)
Check(err)
spt.Time = time.Unix(i, 0)
}

return
}

0 comments on commit f130e30

Please sign in to comment.