From a84d67320e718d73038b5010a46723f50967f6f1 Mon Sep 17 00:00:00 2001 From: Kelly Dwan Date: Wed, 9 Sep 2020 12:33:07 -0400 Subject: [PATCH] Core Data: Bring back support for nested `_fields` values (#25083) * Add a failing test demonstrating the issue * Use lodash functions to check nested keys * Fix undefined meta value --- .../core-data/src/queried-data/selectors.js | 9 ++-- .../src/queried-data/test/selectors.js | 41 +++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/packages/core-data/src/queried-data/selectors.js b/packages/core-data/src/queried-data/selectors.js index a245869a868aa4..364557115de84f 100644 --- a/packages/core-data/src/queried-data/selectors.js +++ b/packages/core-data/src/queried-data/selectors.js @@ -3,6 +3,7 @@ */ import createSelector from 'rememo'; import EquivalentKeyMap from 'equivalent-key-map'; +import { get, has, set } from 'lodash'; /** * Internal dependencies @@ -76,12 +77,12 @@ function getQueriedItemsUncached( state, query ) { // This accounts for the fact that queried items are stored by // stable key without an associated fields query. Other requests // may have included fewer fields properties. - const field = fields[ f ]; - if ( ! item.hasOwnProperty( field ) ) { + const field = fields[ f ].split( '.' ); + if ( ! has( item, field ) ) { return null; } - - filteredItem[ field ] = item[ field ]; + const value = get( item, field ); + set( filteredItem, field, value ); } } else { // If expecting a complete item, validate that completeness, or diff --git a/packages/core-data/src/queried-data/test/selectors.js b/packages/core-data/src/queried-data/test/selectors.js index c02650a32c8e27..5226ae831898cd 100644 --- a/packages/core-data/src/queried-data/test/selectors.js +++ b/packages/core-data/src/queried-data/test/selectors.js @@ -106,6 +106,47 @@ describe( 'getQueriedItems', () => { ] ); } ); + it( 'should dynamically construct fields-filtered item from available data with nested fields', () => { + const state = { + items: { + 1: { + id: 1, + content: 'chicken', + author: 'bob', + meta: { + template: 'single', + _private: 'unused', + }, + }, + 2: { + id: 2, + content: 'ribs', + author: 'sally', + meta: { + template: 'single', + _private: 'unused', + }, + }, + }, + itemIsComplete: { + 1: true, + 2: true, + }, + queries: { + '': [ 1, 2 ], + }, + }; + + const result = getQueriedItems( state, { + _fields: [ 'content', 'meta.template' ], + } ); + + expect( result ).toEqual( [ + { content: 'chicken', meta: { template: 'single' } }, + { content: 'ribs', meta: { template: 'single' } }, + ] ); + } ); + it( 'should return null if attempting to filter by yet-unknown fields', () => { const state = { items: {