Skip to content

Commit

Permalink
Refactor the core-data store to thunks (#28389)
Browse files Browse the repository at this point in the history
* Rename triggerFetch to apiFetch

* Migrate __experimentalBatch

* Inline apiFetch options

* Remove redundant async/awaits

* Remove duplicate comments (likely results of earlier merges)

* Remove controls from the fully thunkified store

* Adjust unit tests

* Restore a few await statements before dispatch.

* Restore await before dispatch( removeItems

* Remove awaits from synchronous calls

Co-authored-by: Adam Zieliński <[email protected]>
  • Loading branch information
jsnajdr and adamziel authored Sep 8, 2021
1 parent fea6b6b commit 70cbe3c
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 140 deletions.
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/core-data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"@wordpress/api-fetch": "file:../api-fetch",
"@wordpress/blocks": "file:../blocks",
"@wordpress/data": "file:../data",
"@wordpress/data-controls": "file:../data-controls",
"@wordpress/deprecated": "file:../deprecated",
"@wordpress/element": "file:../element",
"@wordpress/html-entities": "file:../html-entities",
Expand Down
75 changes: 30 additions & 45 deletions packages/core-data/src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import { v4 as uuid } from 'uuid';
/**
* WordPress dependencies
*/
import { __unstableAwaitPromise } from '@wordpress/data-controls';
import triggerFetch from '@wordpress/api-fetch';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

/**
Expand All @@ -17,7 +16,6 @@ import { addQueryArgs } from '@wordpress/url';
import { receiveItems, removeItems, receiveQueriedItems } from './queried-data';
import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities';
import { createBatch } from './batch';
import { getDispatch } from './controls';
import { STORE_NAME } from './name';

/**
Expand Down Expand Up @@ -168,7 +166,7 @@ export const deleteEntityRecord = (
name,
recordId,
query,
{ __unstableFetch = triggerFetch } = {}
{ __unstableFetch = apiFetch } = {}
) => async ( { dispatch } ) => {
const entities = await dispatch( getKindEntities( kind ) );
const entity = find( entities, { kind, name } );
Expand Down Expand Up @@ -242,7 +240,7 @@ export const editEntityRecord = (
recordId,
edits,
options = {}
) => async ( { select, dispatch } ) => {
) => ( { select, dispatch } ) => {
const entity = select.getEntity( kind, name );
if ( ! entity ) {
throw new Error(
Expand Down Expand Up @@ -270,7 +268,7 @@ export const editEntityRecord = (
}, {} ),
transientEdits,
};
return await dispatch( {
dispatch( {
type: 'EDIT_ENTITY_RECORD',
...edit,
meta: {
Expand Down Expand Up @@ -347,7 +345,7 @@ export const saveEntityRecord = (
kind,
name,
record,
{ isAutosave = false, __unstableFetch = triggerFetch } = {}
{ isAutosave = false, __unstableFetch = apiFetch } = {}
) => async ( { select, resolveSelect, dispatch } ) => {
const entities = await dispatch( getKindEntities( kind ) );
const entity = find( entities, { kind, name } );
Expand All @@ -371,7 +369,7 @@ export const saveEntityRecord = (
const evaluatedValue = value(
select.getEditedEntityRecord( kind, name, recordId )
);
await dispatch.editEntityRecord(
dispatch.editEntityRecord(
kind,
name,
recordId,
Expand All @@ -384,7 +382,7 @@ export const saveEntityRecord = (
}
}

await dispatch( {
dispatch( {
type: 'SAVE_ENTITY_RECORD_START',
kind,
name,
Expand Down Expand Up @@ -436,12 +434,11 @@ export const saveEntityRecord = (
: data.status,
}
);
const options = {
updatedRecord = await __unstableFetch( {
path: `${ path }/autosaves`,
method: 'POST',
data,
};
updatedRecord = await __unstableFetch( options );
} );

// An autosave may be processed by the server as a regular save
// when its update is requested by the author and the post had
Expand Down Expand Up @@ -477,15 +474,15 @@ export const saveEntityRecord = (
},
{}
);
await dispatch.receiveEntityRecords(
dispatch.receiveEntityRecords(
kind,
name,
newRecord,
undefined,
true
);
} else {
await dispatch.receiveAutosaves(
dispatch.receiveAutosaves(
persistedRecord.id,
updatedRecord
);
Expand All @@ -501,13 +498,12 @@ export const saveEntityRecord = (
),
};
}
const options = {
updatedRecord = await __unstableFetch( {
path,
method: recordId ? 'PUT' : 'POST',
data: edits,
};
updatedRecord = await __unstableFetch( options );
await dispatch.receiveEntityRecords(
} );
dispatch.receiveEntityRecords(
kind,
name,
updatedRecord,
Expand All @@ -530,7 +526,7 @@ export const saveEntityRecord = (

return updatedRecord;
} finally {
await dispatch.__unstableReleaseStoreLock( lock );
dispatch.__unstableReleaseStoreLock( lock );
}
};

Expand All @@ -556,52 +552,41 @@ export const saveEntityRecord = (
* @return {Promise} A promise that resolves to an array containing the return
* values of each function given in `requests`.
*/
export function* __experimentalBatch( requests ) {
export const __experimentalBatch = ( requests ) => async ( { dispatch } ) => {
const batch = createBatch();
const dispatch = yield getDispatch();
const api = {
saveEntityRecord( kind, name, record, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).saveEntityRecord( kind, name, record, {
dispatch.saveEntityRecord( kind, name, record, {
...options,
__unstableFetch: add,
} )
);
},
saveEditedEntityRecord( kind, name, recordId, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).saveEditedEntityRecord(
kind,
name,
recordId,
{
...options,
__unstableFetch: add,
}
)
dispatch.saveEditedEntityRecord( kind, name, recordId, {
...options,
__unstableFetch: add,
} )
);
},
deleteEntityRecord( kind, name, recordId, query, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).deleteEntityRecord(
kind,
name,
recordId,
query,
{
...options,
__unstableFetch: add,
}
)
dispatch.deleteEntityRecord( kind, name, recordId, query, {
...options,
__unstableFetch: add,
} )
);
},
};
const resultPromises = requests.map( ( request ) => request( api ) );
const [ , ...results ] = yield __unstableAwaitPromise(
Promise.all( [ batch.run(), ...resultPromises ] )
);
const [ , ...results ] = await Promise.all( [
batch.run(),
...resultPromises,
] );
return results;
}
};

/**
* Action triggered to save an entity record's edits.
Expand Down
31 changes: 0 additions & 31 deletions packages/core-data/src/controls.js

This file was deleted.

3 changes: 0 additions & 3 deletions packages/core-data/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* WordPress dependencies
*/
import { createReduxStore, register } from '@wordpress/data';
import { controls } from '@wordpress/data-controls';

/**
* Internal dependencies
Expand All @@ -12,7 +11,6 @@ import * as selectors from './selectors';
import * as actions from './actions';
import * as resolvers from './resolvers';
import createLocksActions from './locks/actions';
import customControls from './controls';
import { defaultEntities, getMethodName } from './entities';
import { STORE_NAME } from './name';

Expand Down Expand Up @@ -58,7 +56,6 @@ const entityActions = defaultEntities.reduce( ( result, entity ) => {

const storeConfig = () => ( {
reducer,
controls: { ...customControls, ...controls },
actions: { ...actions, ...entityActions, ...createLocksActions() },
selectors: { ...selectors, ...entitySelectors },
resolvers: { ...resolvers, ...entityResolvers },
Expand Down
32 changes: 10 additions & 22 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ import { find, includes, get, hasIn, compact, uniq } from 'lodash';
* WordPress dependencies
*/
import { addQueryArgs } from '@wordpress/url';
import triggerFetch from '@wordpress/api-fetch';
import apiFetch from '@wordpress/api-fetch';

/**
* Internal dependencies
*/
import { STORE_NAME } from './name';

/**
* Internal dependencies
*/
import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities';
import { ifNotResolved, getNormalizedCommaSeparable } from './utils';

Expand All @@ -31,15 +27,15 @@ export const getAuthors = ( query ) => async ( { dispatch } ) => {
'/wp/v2/users/?who=authors&per_page=100',
query
);
const users = await triggerFetch( { path } );
const users = await apiFetch( { path } );
dispatch.receiveUserQuery( path, users );
};

/**
* Requests the current user from the REST API.
*/
export const getCurrentUser = () => async ( { dispatch } ) => {
const currentUser = await triggerFetch( { path: '/wp/v2/users/me' } );
const currentUser = await apiFetch( { path: '/wp/v2/users/me' } );
dispatch.receiveCurrentUser( currentUser );
};

Expand Down Expand Up @@ -106,7 +102,7 @@ export const getEntityRecord = ( kind, name, key = '', query ) => async ( {
}
}

const record = await triggerFetch( { path } );
const record = await apiFetch( { path } );
dispatch.receiveEntityRecords( kind, name, record, query );
} catch ( error ) {
// We need a way to handle and access REST API errors in state
Expand All @@ -132,14 +128,6 @@ export const getEditedEntityRecord = ifNotResolved(
'getRawEntityRecord'
);

/**
* Requests the entity's records from the REST API.
*
* @param {string} kind Entity kind.
* @param {string} name Entity name.
* @param {Object?} query Query Object.
*/

/**
* Requests the entity's records from the REST API.
*
Expand Down Expand Up @@ -181,7 +169,7 @@ export const getEntityRecords = ( kind, name, query = {} ) => async ( {
...query,
} );

let records = Object.values( await triggerFetch( { path } ) );
let records = Object.values( await apiFetch( { path } ) );
// If we request fields but the result doesn't contain the fields,
// explicitely set these fields as "undefined"
// that way we consider the query "fullfilled".
Expand Down Expand Up @@ -237,7 +225,7 @@ getEntityRecords.shouldInvalidate = ( action, kind, name ) => {
* Requests the current theme.
*/
export const getCurrentTheme = () => async ( { dispatch } ) => {
const activeThemes = await triggerFetch( {
const activeThemes = await apiFetch( {
path: '/wp/v2/themes?status=active',
} );
dispatch.receiveCurrentTheme( activeThemes[ 0 ] );
Expand All @@ -247,7 +235,7 @@ export const getCurrentTheme = () => async ( { dispatch } ) => {
* Requests theme supports data from the index.
*/
export const getThemeSupports = () => async ( { dispatch } ) => {
const activeThemes = await triggerFetch( {
const activeThemes = await apiFetch( {
path: '/wp/v2/themes?status=active',
} );
dispatch.receiveThemeSupports( activeThemes[ 0 ].theme_supports );
Expand All @@ -260,7 +248,7 @@ export const getThemeSupports = () => async ( { dispatch } ) => {
*/
export const getEmbedPreview = ( url ) => async ( { dispatch } ) => {
try {
const embedProxyResponse = await triggerFetch( {
const embedProxyResponse = await apiFetch( {
path: addQueryArgs( '/oembed/1.0/proxy', { url } ),
} );
dispatch.receiveEmbedPreview( url, embedProxyResponse );
Expand Down Expand Up @@ -296,7 +284,7 @@ export const canUser = ( action, resource, id ) => async ( { dispatch } ) => {

let response;
try {
response = await triggerFetch( {
response = await apiFetch( {
path,
// Ideally this would always be an OPTIONS request, but unfortunately there's
// a bug in the REST API which causes the Allow header to not be sent on
Expand Down Expand Up @@ -359,7 +347,7 @@ export const getAutosaves = ( postType, postId ) => async ( {
resolveSelect,
} ) => {
const { rest_base: restBase } = await resolveSelect.getPostType( postType );
const autosaves = await triggerFetch( {
const autosaves = await apiFetch( {
path: `/wp/v2/${ restBase }/${ postId }/autosaves?context=edit`,
} );

Expand Down
Loading

0 comments on commit 70cbe3c

Please sign in to comment.