-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathroot-url.js
44 lines (36 loc) · 991 Bytes
/
root-url.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
/**
* Internal dependencies
*/
import namespaceAndEndpointMiddleware from './namespace-endpoint';
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = ( rootURL ) => ( options, next ) => {
return namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if ( typeof path === 'string' ) {
apiRoot = rootURL;
if ( -1 !== rootURL.indexOf( '?' ) ) {
path = path.replace( '?', '&' );
}
path = path.replace( /^\//, '' );
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if (
'string' === typeof apiRoot &&
-1 !== apiRoot.indexOf( '?' )
) {
path = path.replace( '?', '&' );
}
url = apiRoot + path;
}
return next( {
...optionsWithPath,
url,
} );
} );
};
export default createRootURLMiddleware;