Skip to content

Commit

Permalink
API Fetch: Improve isMediaUploadRequest check
Browse files Browse the repository at this point in the history
  • Loading branch information
Mamaduka committed Sep 4, 2021
1 parent 389a1cc commit cc7e3df
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
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 );
} );
} );

0 comments on commit cc7e3df

Please sign in to comment.