From f2474ee250568c8acd6c000fea19ab1db9933b18 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 23 Jul 2018 11:50:24 -0700 Subject: [PATCH] handle nested arrays in toApiFieldNames --- .../usage/classes/__tests__/collector_set.js | 40 ++++++++++++++++++- src/server/usage/classes/collector_set.js | 7 ++-- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/server/usage/classes/__tests__/collector_set.js b/src/server/usage/classes/__tests__/collector_set.js index de50a4fcccba8..3d1a23b8dc5d6 100644 --- a/src/server/usage/classes/__tests__/collector_set.js +++ b/src/server/usage/classes/__tests__/collector_set.js @@ -28,6 +28,7 @@ describe('CollectorSet', () => { let server; let init; let fetch; + beforeEach(() => { server = { log: sinon.spy() }; init = noop; @@ -72,6 +73,12 @@ describe('CollectorSet', () => { }); describe('toApiFieldNames', () => { + let collectorSet; + + beforeEach(() => { + collectorSet = new CollectorSet(); + }); + it('should snake_case and convert field names to api standards', () => { const apiData = { os: { @@ -94,8 +101,7 @@ describe('CollectorSet', () => { ] }; - const collectors = new CollectorSet(); - const result = collectors.toApiFieldNames(apiData); + const result = collectorSet.toApiFieldNames(apiData); expect(result).to.eql({ os: { load: { '15m': 2.3525390625, '1m': 2.22412109375, '5m': 2.4462890625 }, @@ -105,5 +111,35 @@ describe('CollectorSet', () => { days_of_the_week: ['monday', 'tuesday', 'wednesday'], }); }); + + it('should correct object key fields nested in arrays', () => { + const apiData = { + daysOfTheWeek: [ + { + dayName: 'monday', + dayIndex: 1 + }, + { + dayName: 'tuesday', + dayIndex: 2 + }, + { + dayName: 'wednesday', + dayIndex: 3 + } + ] + }; + + const result = collectorSet.toApiFieldNames(apiData); + expect(result).to.eql({ + days_of_the_week: [ + { day_index: 1, day_name: 'monday' }, + { day_index: 2, day_name: 'tuesday' }, + { day_index: 3, day_name: 'wednesday' }, + ], + }); + }); }); }); + + diff --git a/src/server/usage/classes/collector_set.js b/src/server/usage/classes/collector_set.js index 4d19b32fc2523..0c2d4668ee2c4 100644 --- a/src/server/usage/classes/collector_set.js +++ b/src/server/usage/classes/collector_set.js @@ -117,11 +117,12 @@ export class CollectorSet { } }; - if (!Array.isArray(apiData)) { + if (Array.isArray(apiData)) { + return apiData.map(getValueOrRecurse); + } else { return Object.keys(apiData).reduce((accum, field) => { const value = apiData[field]; let newName = field; - newName = snakeCase(newName); newName = newName.replace(/^(1|5|15)_m/, '$1m'); // os.load.15m, os.load.5m, os.load.1m newName = newName.replace('_in_bytes', '_bytes'); @@ -132,8 +133,6 @@ export class CollectorSet { [newName]: getValueOrRecurse(value), }; }, {}); - } else { - return apiData; } } }