Files
mlbstats/internal/statsapi/feed.go

109 lines
1.8 KiB
Go
Raw Normal View History

2024-07-01 23:16:44 -05:00
package statsapi
import (
"encoding/json"
2024-07-03 22:27:36 -05:00
"errors"
2024-07-11 19:42:59 -05:00
"log"
2024-07-03 22:27:36 -05:00
"strconv"
"strings"
2024-07-01 23:16:44 -05:00
)
type FeedParams struct {
GamePk string
}
2024-07-03 22:27:36 -05:00
type FeedResponse map[string]any
2024-07-01 23:16:44 -05: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-11 20:28:02 -05:00
func expand(arr []any, idx int) []any {
2024-07-11 21:50:07 -05:00
var all []any
if idx < len(arr) {
all = arr
} else {
all = make([]any, idx+1)
copy(all[:len(arr)], arr)
all[idx] = make(map[string]any)
}
2024-07-11 20:28:02 -05:00
return all
}
2024-07-11 20:16:32 -05:00
func setValue(obj any, key string, value any) error {
2024-07-03 22:27:36 -05:00
var err error
2024-07-11 20:16:32 -05:00
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
}
2024-07-03 22:27:36 -05:00
2024-07-11 20:28:02 -05:00
v = expand(v, idx)
2024-07-11 20:16:32 -05:00
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)
2024-07-03 22:27:36 -05:00
}
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-09 22:20:45 -05:00
2024-07-11 20:28:02 -05:00
v = expand(v, idx)
2024-07-03 22:27:36 -05:00
err = patch(v[idx], rest, value)
default:
err = errors.New("couldn't determine type")
}
return err
2024-07-03 01:01:02 -05:00
}
2024-07-03 22:27:36 -05:00
func (f *FeedResponse) Patch(instr *instruction) {
2024-07-11 19:42:59 -05:00
log.Println("updating %v to %v", instr.Path, instr.Value)
2024-07-03 22:27:36 -05:00
err := patch(f, instr.Path, instr.Value)
if err != nil {
2024-07-11 19:42:59 -05:00
log.Println(err)
2024-07-03 22:27:36 -05:00
}
2024-07-03 01:01:02 -05:00
}