From 2a94c465bd0aeaa6d2aca5abe741409235dc2f7a Mon Sep 17 00:00:00 2001 From: Jacobo de Vera Date: Mon, 26 Aug 2024 19:38:48 +0100 Subject: [PATCH] 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. --- docs/widgets/services/customapi.md | 3 +++ src/widgets/customapi/component.jsx | 9 +++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/widgets/services/customapi.md b/docs/widgets/services/customapi.md index 477a9e93a..95d2e0551 100644 --- a/docs/widgets/services/customapi.md +++ b/docs/widgets/services/customapi.md @@ -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`. diff --git a/src/widgets/customapi/component.jsx b/src/widgets/customapi/component.jsx index a8fb1f7c6..6acccd3ea 100644 --- a/src/widgets/customapi/component.jsx +++ b/src/widgets/customapi/component.jsx @@ -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;