diff --git a/docs/custom-api.md b/docs/custom-api.md index f4102f7..f065e1b 100644 --- a/docs/custom-api.md +++ b/docs/custom-api.md @@ -415,6 +415,14 @@ The following functions are available on the `JSON` object: - `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects. - `Exists(key string) bool`: Returns true if the key exists in the JSON object. +The following functions are available on the `Options` object: + +- `StringOr(key string, default string) string`: Returns the value of the key as a string, or the default value if the key does not exist. +- `IntOr(key string, default int) int`: Returns the value of the key as an integer, or the default value if the key does not exist. +- `FloatOr(key string, default float) float`: Returns the value of the key as a float, or the default value if the key does not exist. +- `BoolOr(key string, default bool) bool`: Returns the value of the key as a boolean, or the default value if the key does not exist. +- `JSON(key string) JSON`: Returns the value of the key as a stringified `JSON` object, or throws an error if the key does not exist. + The following helper functions provided by Glance are available: - `toFloat(i int) float`: Converts an integer to a float. diff --git a/internal/glance/widget-custom-api.go b/internal/glance/widget-custom-api.go index 1d8bf2f..3c2ca75 100644 --- a/internal/glance/widget-custom-api.go +++ b/internal/glance/widget-custom-api.go @@ -108,6 +108,20 @@ func (o *customAPIOptions) BoolOr(key string, defaultValue bool) bool { return customAPIGetOptionOrDefault(*o, key, defaultValue) } +func (o *customAPIOptions) JSON(key string) string { + value, exists := (*o)[key] + if !exists { + panic(fmt.Sprintf("key %q does not exist in options", key)) + } + + encoded, err := json.Marshal(value) + if err != nil { + panic(fmt.Sprintf("marshaling %s: %v", key, err)) + } + + return string(encoded) +} + func customAPIGetOptionOrDefault[T any](o customAPIOptions, key string, defaultValue T) T { if value, exists := o[key]; exists { if typedValue, ok := value.(T); ok {