From cc7e3df4df45475880cebaef605c53edbd03fc43 Mon Sep 17 00:00:00 2001 From: George Mamadashvili Date: Tue, 31 Aug 2021 15:31:15 +0400 Subject: [PATCH] API Fetch: Improve isMediaUploadRequest check --- .../api-fetch/src/middlewares/media-upload.js | 20 ++++++++--- .../src/middlewares/test/media-upload.js | 35 +++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 packages/api-fetch/src/middlewares/test/media-upload.js diff --git a/packages/api-fetch/src/middlewares/media-upload.js b/packages/api-fetch/src/middlewares/media-upload.js index 2ba4f2953dabff..417abf775db636 100644 --- a/packages/api-fetch/src/middlewares/media-upload.js +++ b/packages/api-fetch/src/middlewares/media-upload.js @@ -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; diff --git a/packages/api-fetch/src/middlewares/test/media-upload.js b/packages/api-fetch/src/middlewares/test/media-upload.js new file mode 100644 index 00000000000000..c0c5b721f67bbb --- /dev/null +++ b/packages/api-fetch/src/middlewares/test/media-upload.js @@ -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 ); + } ); +} );