From 7c70c1ed1b3d7e8d874515dbef7990f5b7656bb3 Mon Sep 17 00:00:00 2001 From: Julie Valet <9500684+julievalet@users.noreply.github.com> Date: Tue, 19 Mar 2024 15:55:02 -0400 Subject: [PATCH] Prevent crashing when no items provided (#141) --- src/helpers.js | 9 ++++----- tests/searchSpec.js | 21 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/helpers.js b/src/helpers.js index cd14b14..026a916 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -247,6 +247,10 @@ export const index = function (items, fields) { let i = 1; + fields.forEach((field) => { + facets['data'][field] = Object.create(null); + }); + items && items.map((item) => { if (!item['_id']) { item['_id'] = i; @@ -258,15 +262,10 @@ export const index = function (items, fields) { items && items.map((item) => { fields.forEach((field) => { - //if (!item || !item[field]) { if (!item) { return; } - if (!facets['data'][field]) { - facets['data'][field] = Object.create(null); - } - if (Array.isArray(item[field])) { item[field].forEach((v) => { if (!item[field]) { diff --git a/tests/searchSpec.js b/tests/searchSpec.js index 7338b4b..2dcece5 100644 --- a/tests/searchSpec.js +++ b/tests/searchSpec.js @@ -65,6 +65,25 @@ describe('search', function () { done(); }); + it('searches no items with filters and query', function test(done) { + const itemsjs = itemsJS([], configuration); + + const result = itemsjs.search({ + filters: { + tags: ['a'], + category: ['drama'], + }, + query: 'comedy', + }); + + assert.equal(result.data.items.length, 0); + assert.equal(result.data.aggregations.in_cinema.buckets.length, 0); + assert.equal(result.data.aggregations.category.buckets.length, 0); + assert.equal(result.data.aggregations.year.buckets.length, 0); + + done(); + }); + it('searches with two filters', function test(done) { const itemsjs = itemsJS(items, configuration); @@ -244,7 +263,7 @@ describe('search', function () { } catch (err) { assert.equal( err.message, - '"query" and "filter" options are not working once native search is disabled', + '"query" and "filter" options are not working once native search is disabled' ); }