mlblive/internal/statsapi/feed.go

103 lines
1.7 KiB
Go

package statsapi
import (
"encoding/json"
"errors"
"log"
"strconv"
"strings"
)
type FeedParams struct {
GamePk string
}
type FeedResponse map[string]any
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
}
func expand(arr []any, idx int) []any {
front := append(arr[:idx], nil)
all := append(front, arr[idx:])
return all
}
func setValue(obj any, key string, value any) error {
var err error
switch v := obj.(type) {
case *FeedResponse:
log.Println("Formerly %v", (*v)[key])
(*v)[key] = value
case map[string]any:
log.Println("Formerly %v", v[key])
v[key] = value
case []any:
idx, err := strconv.Atoi(key)
if err != nil {
break
}
v = expand(v, idx)
v[idx] = value
default:
err = errors.New("couldn't determine type")
}
return err
}
func patch(obj any, path string, value any) error {
var err error
first, rest, found := strings.Cut(path, "/")
if !found {
setValue(obj, first, value)
}
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
}
v = expand(v, idx)
err = patch(v[idx], rest, value)
default:
err = errors.New("couldn't determine type")
}
return err
}
func (f *FeedResponse) Patch(instr *instruction) {
log.Println("updating %v to %v", instr.Path, instr.Value)
err := patch(f, instr.Path, instr.Value)
if err != nil {
log.Println(err)
}
}