Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Fetch: Improve isMediaUploadRequest check #34417

Merged
merged 1 commit into from
Sep 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions packages/api-fetch/src/middlewares/media-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,29 @@ import {
parseResponseAndNormalizeError,
} from '../utils/response';

/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest( options ) {
const isCreateMethod = !! options.method && options.method === 'POST';
const isMediaEndpoint =
( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||
( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );

return isMediaEndpoint && isCreateMethod;
}

/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = ( options, next ) => {
const isMediaUploadRequest =
( options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||
( options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );

if ( ! isMediaUploadRequest ) {
if ( ! isMediaUploadRequest( options ) ) {
return next( options );
}

let retries = 0;
const maxRetries = 5;

Expand Down
35 changes: 35 additions & 0 deletions packages/api-fetch/src/middlewares/test/media-upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Internal dependencies
*/
import mediaUploadMiddleware from '../media-upload';

describe( 'Media Upload Middleware', () => {
it( 'should defer to the next middleware with the same options', () => {
expect.hasAssertions();

const originalOptions = { path: '/wp/v2/media' };
const next = ( options ) => {
expect( options ).toBe( originalOptions );
};

mediaUploadMiddleware( originalOptions, next );
} );

it( 'should change options not to parse', () => {
expect.hasAssertions();

const requestOptions = { method: 'POST', path: '/wp/v2/media' };
const next = ( options ) => {
expect( options.parse ).toBe( false );

return Promise.resolve( {
status: 200,
json() {
return Promise.resolve( [ 'item' ] );
},
} );
};

mediaUploadMiddleware( requestOptions, next );
} );
} );