-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
api-fetch-setup.js
49 lines (41 loc) · 1.38 KB
/
api-fetch-setup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* WordPress dependencies
*/
import { fetchRequest } from '@wordpress/react-native-bridge';
import apiFetch from '@wordpress/api-fetch';
// Please add only wp.org API paths here!
const SUPPORTED_ENDPOINTS = [
/wp\/v2\/(media|categories|blocks)\/?\d*?.*/i,
/wp\/v2\/search\?.*/i,
];
const setTimeoutPromise = ( delay ) =>
new Promise( ( resolve ) => setTimeout( resolve, delay ) );
const fetchHandler = ( { path }, retries = 20, retryCount = 1 ) => {
if ( ! isPathSupported( path ) ) {
return Promise.reject( `Unsupported path: ${ path }` );
}
const responsePromise = fetchRequest( path );
const parseResponse = ( response ) => {
if ( typeof response === 'string' ) {
response = JSON.parse( response );
}
return response;
};
return responsePromise.then( parseResponse ).catch( ( error ) => {
// eslint-disable-next-line no-console
console.warn( 'Network Error: ', JSON.stringify( error, null, 2 ) );
if ( error.code >= 400 && error.code < 600 ) {
return error;
} else if ( retries === 0 ) {
return Promise.reject( error );
}
return setTimeoutPromise( 1000 * retryCount ).then( () =>
fetchHandler( { path }, retries - 1, retryCount + 1 )
);
} );
};
export const isPathSupported = ( path ) =>
SUPPORTED_ENDPOINTS.some( ( pattern ) => pattern.test( path ) );
export default () => {
apiFetch.setFetchHandler( ( options ) => fetchHandler( options ) );
};