From aae0d71799eee8998779ac5c4bc2d31f9fd1cd10 Mon Sep 17 00:00:00 2001 From: Ralph Ocdol Date: Mon, 23 Jun 2025 20:18:05 +0800 Subject: [PATCH] Added Object helper for custom-api --- internal/glance/widget-custom-api.go | 31 ++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/internal/glance/widget-custom-api.go b/internal/glance/widget-custom-api.go index 3c2ca75..3ae1e4e 100644 --- a/internal/glance/widget-custom-api.go +++ b/internal/glance/widget-custom-api.go @@ -357,6 +357,11 @@ type decoratedGJSONResult struct { gjson.Result } +type ObjectProperty struct { + Key string + Value decoratedGJSONResult +} + func gJsonResultArrayToDecoratedResultArray(results []gjson.Result) []decoratedGJSONResult { decoratedResults := make([]decoratedGJSONResult, len(results)) @@ -415,6 +420,32 @@ func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult { return &decoratedGJSONResult{r.Result.Get(key)} } +func gjsonResultObjectToPropertyArray(obj gjson.Result) []ObjectProperty { + results := make([]ObjectProperty, 0) + obj.ForEach(func(k, v gjson.Result) bool { + results = append(results, ObjectProperty{ + Key: k.String(), + Value: decoratedGJSONResult{v}, + }) + return true + }) + return results +} + +func (r *decoratedGJSONResult) Object(key string) []ObjectProperty { + var obj gjson.Result + if key == "" { + obj = r.Result + } else { + obj = r.Result.Get(key) + } + + if !obj.IsObject() { + return []ObjectProperty{} + } + return gjsonResultObjectToPropertyArray(obj) +} + func customAPIDoMathOp[T int | float64](a, b T, op string) T { switch op { case "add":