Skip to content

Commit

Permalink
Core Data: Bring back support for nested _fields values (#25083)
Browse files Browse the repository at this point in the history
* Add a failing test demonstrating the issue

* Use lodash functions to check nested keys

* Fix undefined meta value
  • Loading branch information
ryelle authored Sep 9, 2020
1 parent a2e828e commit a84d673
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/core-data/src/queried-data/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import createSelector from 'rememo';
import EquivalentKeyMap from 'equivalent-key-map';
import { get, has, set } from 'lodash';

/**
* Internal dependencies
Expand Down Expand Up @@ -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
Expand Down
41 changes: 41 additions & 0 deletions packages/core-data/src/queried-data/test/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down

0 comments on commit a84d673

Please sign in to comment.