mlblive/internal/statsapi/feed.go

109 lines
1.8 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"
2024-07-12 00:42:59 +00:00
"log"
2024-07-04 03:27:36 +00:00
"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-12 01:28:02 +00:00
func expand(arr []any, idx int) []any {
2024-07-12 02:50:07 +00: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-12 01:28:02 +00:00
return all
}
2024-07-12 01:16:32 +00:00
func setValue(obj any, key string, value any) error {
2024-07-04 03:27:36 +00:00
var err error
2024-07-12 01:16:32 +00: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-04 03:27:36 +00:00
2024-07-12 01:28:02 +00:00
v = expand(v, idx)
2024-07-12 01:16:32 +00: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-04 03:27:36 +00: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-10 03:20:45 +00:00
2024-07-12 01:28:02 +00:00
v = expand(v, idx)
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) {
2024-07-12 00:42:59 +00:00
log.Println("updating %v to %v", instr.Path, instr.Value)
2024-07-04 03:27:36 +00:00
err := patch(f, instr.Path, instr.Value)
if err != nil {
2024-07-12 00:42:59 +00:00
log.Println(err)
2024-07-04 03:27:36 +00:00
}
2024-07-03 06:01:02 +00:00
}