diff --git a/pick.go b/pick.go index 5522627..1241b2f 100644 --- a/pick.go +++ b/pick.go @@ -1,7 +1,9 @@ package pick import ( + "bytes" "encoding/json" + "io" "github.com/moukoublen/pick/cast" ) @@ -15,22 +17,27 @@ type Traverser interface { Get(m any, selector []SelectorKey) (any, error) } -func Wrap(data any) *Picker { - caster := cast.NewCaster() - formatter := DefaultSelectorFormat{} - return NewPicker(data, NewDefaultTraverser(caster), caster, formatter) +func WrapJSON(js []byte) (*Picker, error) { + return WrapReaderJSON(bytes.NewReader(js)) } -func WrapJSON(js []byte) (*Picker, error) { +func WrapReaderJSON(r io.Reader) (*Picker, error) { + d := json.NewDecoder(r) + return WrapDecoder(d) +} + +func WrapDecoder(decoder interface{ Decode(destination any) error }) (*Picker, error) { m := map[string]any{} - err := json.Unmarshal(js, &m) - if err != nil { + if err := decoder.Decode(&m); err != nil { return nil, err } + return Wrap(m), nil +} + +func Wrap(data any) *Picker { caster := cast.NewCaster() - formatter := DefaultSelectorFormat{} - return NewPicker(m, NewDefaultTraverser(caster), caster, formatter), nil + return NewPicker(data, NewDefaultTraverser(caster), caster, DefaultSelectorFormat{}) } type Picker struct { @@ -40,12 +47,12 @@ type Picker struct { selectorFormat SelectorFormat } -func NewPicker(inner any, t Traverser, c Caster, selectorFormat SelectorFormat) *Picker { +func NewPicker(data any, t Traverser, c Caster, s SelectorFormat) *Picker { return &Picker{ - inner: inner, + inner: data, traverser: t, caster: c, - selectorFormat: selectorFormat, + selectorFormat: s, } } diff --git a/pick_test.go b/pick_test.go index 8fe8342..57e6dff 100644 --- a/pick_test.go +++ b/pick_test.go @@ -2,8 +2,8 @@ package pick import ( "embed" - "encoding/json" "fmt" + "io/fs" "path/filepath" "reflect" "testing" @@ -115,7 +115,7 @@ func TestString(t *testing.T) { //go:embed internal/testingx/testdata var testData embed.FS -func loadTestData(t *testing.T, filename string, decodeInto any) { +func loadTestData(t *testing.T, filename string) (fs.File, error) { t.Helper() path := filepath.Join("internal", "testingx", "testdata", filename) @@ -124,17 +124,21 @@ func loadTestData(t *testing.T, filename string, decodeInto any) { t.Fatalf("error during testdate file opening %s", err.Error()) } - if err := json.NewDecoder(f).Decode(decodeInto); err != nil { - t.Fatalf("error during testdate file decoding %s", err.Error()) - } + return f, nil } func TestNasaDataFile(t *testing.T) { t.Parallel() - inner := map[string]any{} - loadTestData(t, "nasa.json", &inner) - ob := Wrap(inner) + file, err := loadTestData(t, "nasa.json") + if err != nil { + t.Fatal(err) + } + + ob, err := WrapReaderJSON(file) + if err != nil { + t.Fatal(err) + } tests := []struct { accessFn any