Skip to content
Open
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
5 changes: 3 additions & 2 deletions src/utils/api-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,11 @@ function apiPathModifierMiddleware( options, next ) {
).test( options.path ) || /\/sites\/[^/]+\//.test( options.path );

if ( isEligiblePath && ! alreadyHasSiteNamespace ) {
// Insert the API namespace after the first two path segments.
// Insert the API namespace after the first two path segments, with a
// single trailing slash.
options.path = options.path.replace(
/^(?<apiPath>\/?(?:[\w.-]+\/){2})/,
`$<apiPath>${ siteApiNamespace[ 0 ] }`
`$<apiPath>${ siteApiNamespace[ 0 ].replace( /\/+$/, '' ) }/`
);
}

Expand Down
27 changes: 27 additions & 0 deletions src/utils/api-fetch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,33 @@ describe( 'api-fetch credentials handling', () => {
expect( requestedUrl() ).toContain( '/wp/v2/sites/123/posts' );
} );

it( 'inserts a namespace configured without a trailing slash', async () => {
// Both forms are supported; the native URL builders normalize them
// identically. Without normalizing here the namespace would run into
// the following segment: `/wp/v2/sites/123posts`.
bridge.getGBKit.mockReturnValue( {
siteApiRoot: 'https://example.com/wp-json/',
siteApiNamespace: [ 'sites/123' ],
namespaceExcludedPaths: [],
} );

await apiFetch( { path: '/wp/v2/posts' } ).catch( () => {} );

expect( requestedUrl() ).toContain( '/wp/v2/sites/123/posts' );
} );

it( 'does not double the slash on a namespace that already ends with one', async () => {
bridge.getGBKit.mockReturnValue( {
siteApiRoot: 'https://example.com/wp-json/',
siteApiNamespace: [ 'sites/123/' ],
namespaceExcludedPaths: [],
} );

await apiFetch( { path: '/wp/v2/posts' } ).catch( () => {} );

expect( requestedUrl() ).not.toContain( 'sites/123//' );
} );

it( 'leaves the path alone when it already carries the namespace', async () => {
bridge.getGBKit.mockReturnValue( {
siteApiRoot: 'https://example.com/wp-json/',
Expand Down
Loading