Feature: Support selecting the top level of a Custom API response

Some APIs return arrays at the top. With this change, a customapi widget
can select the top level object/array.

This is particularly useful when combined with the `size` formatter, but
can also be used for APIs that return scalar values directly.
This commit is contained in:
Jacobo de Vera
2024-08-26 19:38:48 +01:00
parent 4318cd6537
commit 2a94c465bd
2 changed files with 10 additions and 2 deletions

View File

@@ -57,6 +57,9 @@ widget:
- field: key
label: Number of things in array
format: size
- field: . # This will take the root of the API response, e.g. when APIs return an array
label: Number of items
format: size
```
Supported formats for the values are `text`, `number`, `float`, `percent`, `bytes`, `bitrate`, `size`, `date` and `relativeDate`.

View File

@@ -5,9 +5,9 @@ import Block from "components/services/widget/block";
import useWidgetAPI from "utils/proxy/use-widget-api";
function getLength(data) {
if ('length' in data) {
if ("length" in data) {
return data.length;
} else if (typeof data === 'object' && data !== null) {
} else if (typeof data === "object" && data !== null) {
return Object.keys(data).length;
} else {
return NaN;
@@ -19,6 +19,11 @@ function getValue(field, data) {
let lastField = field;
let key = "";
// Support APIs that return arrays or scalars directly.
if (field === ".") {
return value;
}
while (typeof lastField === "object") {
key = Object.keys(lastField)[0] ?? null;