adds list response parsing to api service (#30455)

This commit is contained in:
Jordan Reimer 2025-04-30 13:13:35 -06:00 committed by GitHub
parent 899e66b2d8
commit c0d05cd7b3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 35 additions and 0 deletions

View File

@ -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<string, unknown>; 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<string, unknown>[]
);
}
}

View File

@ -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 = {