From 4162918198844cec2fa7dbbc50d469b565d47b87 Mon Sep 17 00:00:00 2001 From: Guido Modarelli Date: Wed, 11 Sep 2024 17:51:48 -0300 Subject: [PATCH] Refactor parseData to handle generic source type --- .../data-grid/data-grid-service.test.ts | 47 +++++++++++++++++++ .../common/data-grid/data-grid-service.ts | 12 ++++- 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 plugins/main/public/components/common/data-grid/data-grid-service.test.ts diff --git a/plugins/main/public/components/common/data-grid/data-grid-service.test.ts b/plugins/main/public/components/common/data-grid/data-grid-service.test.ts new file mode 100644 index 0000000000..cfc58ff671 --- /dev/null +++ b/plugins/main/public/components/common/data-grid/data-grid-service.test.ts @@ -0,0 +1,47 @@ +import { parseData } from './data-grid-service'; +import { SearchResponse } from '../../../../../../src/core/server'; + +describe('describe-grid-test', () => { + describe('parseData', () => { + it('should parse data extract source fields correctly', () => { + const resultsHits: SearchResponse['hits']['hits'] = [ + { + _id: 'id-1', + _index: 'index-1', + _type: 'type-1', + _score: 1, + _source: { + test: true, + }, + }, + ]; + + const expectedResult = [ + { + _id: 'id-1', + _index: 'index-1', + _type: 'type-1', + _score: 1, + test: true, + }, + ]; + + expect(parseData(resultsHits)).toEqual(expectedResult); + }); + + it('should parse data handle invalid hits', () => { + const resultsHits: SearchResponse['hits']['hits'] = [ + // @ts-expect-error + undefined, + // @ts-expect-error + null, + // @ts-expect-error + 0, + ]; + + const expectedResult = [{}, {}, {}]; + + expect(parseData(resultsHits)).toEqual(expectedResult); + }); + }); +}); diff --git a/plugins/main/public/components/common/data-grid/data-grid-service.ts b/plugins/main/public/components/common/data-grid/data-grid-service.ts index 8e2ea334d6..5db28b3856 100644 --- a/plugins/main/public/components/common/data-grid/data-grid-service.ts +++ b/plugins/main/public/components/common/data-grid/data-grid-service.ts @@ -8,12 +8,20 @@ import { tDataGridColumn } from './use-data-grid'; import { cellFilterActions } from './cell-filter-actions'; import { FILTER_OPERATOR, PatternDataSourceFilterManager } from '../data-source'; -export const parseData = (resultsHits: SearchResponse['hits']['hits']): any[] => { +type ParseData = { + source: T, + _id: string, + _index: string, + _type: string, + _score: number, +} | {} + +export const parseData = (resultsHits: SearchResponse['hits']['hits']): ParseData[] => { const data = resultsHits.map((hit) => { if (!hit) { return {}; } - const source = hit._source as object; + const source = hit._source as T; const data = { ...source, _id: hit._id,