Skip to content

Commit

Permalink
Use apiFetch instead of window.fetch (#50043)
Browse files Browse the repository at this point in the history
* Use apiFetch instead of window.fetch

* add comment

* Fix mocking in test

---------

Co-authored-by: scruffian <ben@scruffian.com>
Co-authored-by: Dave Smith <getdavemail@gmail.com>
  • Loading branch information
3 people authored Apr 27, 2023
1 parent e8ec1ce commit 254d13f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 21 deletions.
14 changes: 7 additions & 7 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,15 +409,15 @@ export const getAutosave =
export const __experimentalGetTemplateForLink =
( link ) =>
async ( { dispatch, resolveSelect } ) => {
// Ideally this should be using an apiFetch call
// We could potentially do so by adding a "filter" to the `wp_template` end point.
// Also it seems the returned object is not a regular REST API post type.
let template;
try {
template = await window
.fetch( addQueryArgs( link, { '_wp-find-template': true } ) )
.then( ( res ) => res.json() )
.then( ( { data } ) => data );
// This is NOT calling a REST endpoint but rather ends up with a response from
// an Ajax function which has a different shape from a WP_REST_Response.
template = await apiFetch( {
url: addQueryArgs( link, {
'_wp-find-template': true,
} ),
} ).then( ( { data } ) => data );
} catch ( e ) {
// For non-FSE themes, it is possible that this request returns an error.
}
Expand Down
20 changes: 6 additions & 14 deletions packages/edit-site/src/store/test/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,21 +168,13 @@ describe( 'actions', () => {
const ID = 'emptytheme//single';
const SLUG = 'single';

window.fetch = async ( path ) => {
if ( path === '/?_wp-find-template=true' ) {
return {
json: async () => ( { data: { id: ID, slug: SLUG } } ),
};
}

throw {
code: 'unknown_path',
message: `Unknown path: ${ path }`,
};
};

apiFetch.setFetchHandler( async ( options ) => {
const { method = 'GET', path } = options;
const { method = 'GET', path, url } = options;

// Called with url arg in `__experimentalGetTemplateForLink`
if ( url ) {
return { data: { id: ID, slug: SLUG } };
}

if ( method === 'GET' ) {
if ( path.startsWith( '/wp/v2/types' ) ) {
Expand Down

0 comments on commit 254d13f

Please sign in to comment.