Skip to content

Commit

Permalink
fix: work around invalid all_time_since_today data schema to fix fail…
Browse files Browse the repository at this point in the history
…ing import (resolve #370)
  • Loading branch information
muety committed May 11, 2022
1 parent 1b7baf6 commit 09d1124
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
6 changes: 4 additions & 2 deletions services/imports/wakatime.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"github.com/duke-git/lancet/v2/datetime"
"github.com/muety/wakapi/utils"
"net/http"
"time"

Expand Down Expand Up @@ -154,8 +155,9 @@ func (w *WakatimeHeartbeatImporter) fetchRange(baseUrl string) (time.Time, time.
return notime, notime, err
}

var allTimeData wakatime.AllTimeViewModel
if err := json.NewDecoder(res.Body).Decode(&allTimeData); err != nil {
// see https://github.com/muety/wakapi/issues/370
allTimeData, err := utils.ParseJsonDropKeys[wakatime.AllTimeViewModel](res.Body, "text")
if err != nil {
return notime, notime, err
}

Expand Down
34 changes: 34 additions & 0 deletions utils/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package utils

import (
"bytes"
"encoding/json"
"io"
)

// ParseJsonDropKeys parses the given JSON input object to an object of given type, while omitting the specified keys on the way.
// This can be useful if parsing would normally fail due to ambiguous typing of some key, but that key is not of interest and can be dropped to avoid parse errors.
// Dropping keys only works on top level of the object.
func ParseJsonDropKeys[T any](r io.Reader, dropKeys ...string) (T, error) {
var (
result T
resultTmp map[string]interface{}
resultTmpBuf = new(bytes.Buffer)
)
if err := json.NewDecoder(r).Decode(&resultTmp); err != nil {
return result, err
}

for _, k := range dropKeys {
delete(resultTmp, k)
}

if err := json.NewEncoder(resultTmpBuf).Encode(resultTmp); err != nil {
return result, err
}
if err := json.NewDecoder(resultTmpBuf).Decode(&result); err != nil {
return result, err
}

return result, nil
}

0 comments on commit 09d1124

Please sign in to comment.