mirror of
https://github.com/pocketbase/pocketbase.git
synced 2025-01-22 05:39:49 +02:00
adde json map Get and Set helpers
This commit is contained in:
parent
ed4304dc30
commit
1adcfcc03b
@ -21,6 +21,22 @@ func (m JsonMap) MarshalJSON() ([]byte, error) {
|
|||||||
return json.Marshal(alias(m))
|
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.
|
// Value implements the [driver.Valuer] interface.
|
||||||
func (m JsonMap) Value() (driver.Value, error) {
|
func (m JsonMap) Value() (driver.Value, error) {
|
||||||
data, err := json.Marshal(m)
|
data, err := json.Marshal(m)
|
||||||
|
@ -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) {
|
func TestJsonMapValue(t *testing.T) {
|
||||||
scenarios := []struct {
|
scenarios := []struct {
|
||||||
json types.JsonMap
|
json types.JsonMap
|
||||||
|
Loading…
x
Reference in New Issue
Block a user