mlblive/internal/statsapi/feed.go

112 lines
2.2 KiB
Go
Raw Normal View History

2024-07-02 04:16:44 +00:00
package statsapi
import (
"encoding/json"
2024-07-04 03:27:36 +00:00
"errors"
"strconv"
"strings"
2024-07-02 04:16:44 +00:00
)
type FeedParams struct {
GamePk string
}
2024-07-04 03:27:36 +00:00
type FeedResponse map[string]any
2024-07-02 04:16:44 +00:00
type Play struct {
Result result
About about
AtBatIndex int
}
type result struct {
Event string
Description string
RBI int
AwayScore int
HomeScore int
}
type about struct {
AtBatIndex json.Number
IsTopInning bool
Inning json.Number
IsScoringPlay bool
CaptivatingIndex json.Number
}
2024-07-04 03:27:36 +00:00
func patch(obj any, path string, value any) error {
if string(path[0]) == "/" {
path = path[1:]
}
2024-07-03 06:01:02 +00:00
2024-07-04 03:27:36 +00:00
var err error
first, rest, found := strings.Cut(path, "/")
if !found {
switch v := obj.(type) {
case *FeedResponse:
(*v)[first] = value
case map[string]any:
v[first] = value
case []any:
idx, err := strconv.Atoi(first)
if err != nil {
break
}
if idx < len(v) {
v[idx] = value
} else {
v = append(v, value)
}
default:
err = errors.New("couldn't determine type")
}
return err
}
switch v := obj.(type) {
case *FeedResponse:
err = patch((*v)[first], rest, value)
case map[string]any:
err = patch(v[first], rest, value)
case []any:
idx, err := strconv.Atoi(first)
if err != nil {
break
}
err = patch(v[idx], rest, value)
default:
err = errors.New("couldn't determine type")
}
return err
2024-07-03 06:01:02 +00:00
}
2024-07-04 03:27:36 +00:00
func (f *FeedResponse) Patch(instr *instruction) {
err := patch(f, instr.Path, instr.Value)
if err != nil {
}
2024-07-03 06:01:02 +00:00
}
2024-07-02 04:16:44 +00:00
func (p *Play) Patch(patch Patch) {
instructions := patch.Diff
stem := "/liveData/plays/currentPlay"
for _, i := range instructions {
if i.Op == "add" && i.Path == stem+"/result/description" {
p.Result.Description = i.Value.(string)
} else if i.Op == "replace" && i.Path == stem+"/about/isScoringPlay" {
p.About.IsScoringPlay = i.Value.(bool)
} else if i.Op == "replace" && i.Path == stem+"/result/homeScore" {
p.Result.HomeScore = int(i.Value.(float64))
} else if i.Op == "replace" && i.Path == stem+"/result/awayScore" {
p.Result.AwayScore = int(i.Value.(float64))
} else if i.Op == "add" && i.Path == stem+"/result/event" {
p.Result.Event = i.Value.(string)
} else if i.Op == "replace" && i.Path == stem+"/atBatIndex" {
p.AtBatIndex = int(i.Value.(float64))
}
}
}