From c0d05cd7b3c6d4ac54eb97a9b58f82bbf6f623b3 Mon Sep 17 00:00:00 2001 From: Jordan Reimer Date: Wed, 30 Apr 2025 13:13:35 -0600 Subject: [PATCH] adds list response parsing to api service (#30455) --- ui/app/services/api.ts | 19 +++++++++++++++++++ ui/tests/unit/services/api-test.js | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/ui/app/services/api.ts b/ui/app/services/api.ts index 67a6e43f34..4325b57996 100644 --- a/ui/app/services/api.ts +++ b/ui/app/services/api.ts @@ -181,4 +181,23 @@ export default class ApiService extends Service { message: (e as Error)?.message || fallbackMessage, }; } + + // accepts a list response as { keyInfo, keys } and returns a flat array of the keyInfo datum + // to preserve the keys (unique identifiers) the value will be set on the datum as id + keyInfoToArray(response: unknown = {}) { + const { keyInfo, keys } = response as { keyInfo?: Record; keys?: string[] }; + if (!keyInfo || !keys) { + return []; + } + return keys.reduce( + (arr, key) => { + const datum = keyInfo[key]; + if (datum) { + arr.push({ id: key, ...datum }); + } + return arr; + }, + [] as Record[] + ); + } } diff --git a/ui/tests/unit/services/api-test.js b/ui/tests/unit/services/api-test.js index 8dadb7e7c7..1f41ca4c96 100644 --- a/ui/tests/unit/services/api-test.js +++ b/ui/tests/unit/services/api-test.js @@ -170,6 +170,22 @@ module('Unit | Service | api', function (hooks) { ); }); + test('it should map list response to array', async function (assert) { + const response = { + keyInfo: { + key1: { title: 'Title 1' }, + key2: { title: 'Title 2' }, + }, + keys: ['key1', 'key2'], + }; + const expectedResponse = [ + { id: 'key1', title: 'Title 1' }, + { id: 'key2', title: 'Title 2' }, + ]; + const listData = this.apiService.keyInfoToArray(response); + assert.deepEqual(listData, expectedResponse, 'List response is mapped to array'); + }); + module('Error parsing', function (hooks) { hooks.beforeEach(function () { this.response = {