mlblive/internal/statsapi/feed.go

101 lines
1.6 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
}
2024-07-10 03:20:45 +00:00
if len(v) <= idx {
arr := make([]any, idx+1)
for i, val := range v {
arr[i] = val
}
v = arr
}
2024-07-04 03:27:36 +00:00
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
}