From e782531f252c964860365eff88405d0e52a7eb7a Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Wed, 10 Feb 2021 01:32:13 +0300 Subject: [PATCH] [#255] pkg/object: Implement json.Marshaler/Unmarshaler on SearchFilters Signed-off-by: Leonard Lyubich --- pkg/object/search.go | 19 +++++++++++++++++++ pkg/object/search_test.go | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/pkg/object/search.go b/pkg/object/search.go index 208fcf4..84c3303 100644 --- a/pkg/object/search.go +++ b/pkg/object/search.go @@ -1,6 +1,7 @@ package object import ( + "encoding/json" "fmt" "github.com/nspcc-dev/neofs-api-go/pkg" @@ -255,3 +256,21 @@ func (f *SearchFilters) AddSplitIDFilter(m SearchMatchType, id *SplitID) { func (f *SearchFilters) AddTypeFilter(m SearchMatchType, typ Type) { f.addReservedFilter(m, fKeyType, typ) } + +// MarshalJSON encodes SearchFilters to protobuf JSON format. +func (f *SearchFilters) MarshalJSON() ([]byte, error) { + return json.Marshal(f.ToV2()) +} + +// UnmarshalJSON decodes SearchFilters from protobuf JSON format. +func (f *SearchFilters) UnmarshalJSON(data []byte) error { + var fsV2 []*v2object.SearchFilter + + if err := json.Unmarshal(data, &fsV2); err != nil { + return err + } + + *f = NewSearchFiltersFromV2(fsV2) + + return nil +} diff --git a/pkg/object/search_test.go b/pkg/object/search_test.go index 573d06b..62cca9b 100644 --- a/pkg/object/search_test.go +++ b/pkg/object/search_test.go @@ -176,3 +176,19 @@ func TestSearchFilters_AddTypeFilter(t *testing.T) { require.Equal(t, v2object.MatchStringEqual, fsV2[0].GetMatchType()) }) } + +func TestSearchFiltersEncoding(t *testing.T) { + fs := object.NewSearchFilters() + fs.AddFilter("key 1", "value 2", object.MatchStringEqual) + fs.AddFilter("key 2", "value 2", object.MatchStringNotEqual) + + t.Run("json", func(t *testing.T) { + data, err := fs.MarshalJSON() + require.NoError(t, err) + + fs2 := object.NewSearchFilters() + require.NoError(t, fs2.UnmarshalJSON(data)) + + require.Equal(t, fs, fs2) + }) +}