From 1adcfcc03b96b5609e6233adf264b1a92f1cab3f Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Tue, 20 Jun 2023 22:57:51 +0300 Subject: [PATCH] adde json map Get and Set helpers --- tools/types/json_map.go | 16 +++++++++++++++ tools/types/json_map_test.go | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/tools/types/json_map.go b/tools/types/json_map.go index 6358959c..bb2b14ec 100644 --- a/tools/types/json_map.go +++ b/tools/types/json_map.go @@ -21,6 +21,22 @@ func (m JsonMap) MarshalJSON() ([]byte, error) { return json.Marshal(alias(m)) } +// Get retrieves a single value from the current JsonMap. +// +// This helper was added primarily to assist the goja integration since custom map types +// don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). +func (m JsonMap) Get(key string) any { + return m[key] +} + +// Set sets a single value in the current JsonMap. +// +// This helper was added primarily to assist the goja integration since custom map types +// don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). +func (m JsonMap) Set(key string, value any) { + m[key] = value +} + // Value implements the [driver.Valuer] interface. func (m JsonMap) Value() (driver.Value, error) { data, err := json.Marshal(m) diff --git a/tools/types/json_map_test.go b/tools/types/json_map_test.go index c0e5628d..1c396df6 100644 --- a/tools/types/json_map_test.go +++ b/tools/types/json_map_test.go @@ -30,6 +30,46 @@ func TestJsonMapMarshalJSON(t *testing.T) { } } +func TestJsonMapGet(t *testing.T) { + scenarios := []struct { + json types.JsonMap + key string + expected any + }{ + {nil, "test", nil}, + {types.JsonMap{"test": 123}, "test", 123}, + {types.JsonMap{"test": 123}, "missing", nil}, + } + + for i, s := range scenarios { + result := s.json.Get(s.key) + if result != s.expected { + t.Errorf("(%d) Expected %s, got %v", i, s.expected, result) + } + } +} + +func TestJsonMapSet(t *testing.T) { + scenarios := []struct { + key string + value any + }{ + {"a", nil}, + {"a", 123}, + {"b", "test"}, + } + + for i, s := range scenarios { + j := types.JsonMap{} + + j.Set(s.key, s.value) + + if v := j[s.key]; v != s.value { + t.Errorf("(%d) Expected %s, got %v", i, s.value, v) + } + } +} + func TestJsonMapValue(t *testing.T) { scenarios := []struct { json types.JsonMap