Skip to content
Merged
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
6 changes: 6 additions & 0 deletions packages/api-fetch/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 2.3.0 (Unreleased)

### New Feature

- Default fetch handler can be overridden with a custom fetch handler

## 2.2.6 (2018-12-12)

## 2.2.5 (2018-11-20)
Expand Down
23 changes: 23 additions & 0 deletions packages/api-fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,27 @@ const rootURL = "http://my-wordpress-site/wp-json/";
apiFetch.use( apiFetch.createRootURLMiddleware( rootURL ) );
```

### Custom fetch handler

The `api-fetch` package uses `window.fetch` for making the requests but you can use a custom fetch handler by using the `setFetchHandler` method. The custom fetch handler will receive the `options` passed to the `apiFetch` calls.

**Example**

The example below uses a custom fetch handler for making all the requests with [`axios`](https://github.com/axios/axios).

```js
import apiFetch from '@wordpress/api-fetch';
import axios from 'axios';

apiFetch.setFetchHandler( ( options ) => {
const { url, path, data, method } = options;

return axios( {
url: url || path,
method,
data,
} );
} );
```

<br/><br/><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>
175 changes: 95 additions & 80 deletions packages/api-fetch/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,106 +38,121 @@ const DEFAULT_OPTIONS = {
credentials: 'include',
};

const middlewares = [];
const middlewares = [
userLocaleMiddleware,
namespaceEndpointMiddleware,
httpV1Middleware,
fetchAllMiddleware,
];

function registerMiddleware( middleware ) {
middlewares.push( middleware );
middlewares.unshift( middleware );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, much easier to follow than using reverse on the list of middlewares 👍

}

function apiFetch( options ) {
const raw = ( nextOptions ) => {
const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
let { body, headers } = nextOptions;
const defaultFetchHandler = ( nextOptions ) => {
const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
let { body, headers } = nextOptions;

// Merge explicitly-provided headers with default values.
headers = { ...DEFAULT_HEADERS, ...headers };

// The `data` property is a shorthand for sending a JSON body.
if ( data ) {
body = JSON.stringify( data );
headers[ 'Content-Type' ] = 'application/json';
}

const responsePromise = window.fetch(
url || path,
{
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers,
}
);
const checkStatus = ( response ) => {
if ( response.status >= 200 && response.status < 300 ) {
return response;
}

throw response;
};

// Merge explicitly-provided headers with default values.
headers = { ...DEFAULT_HEADERS, ...headers };
const parseResponse = ( response ) => {
if ( parse ) {
if ( response.status === 204 ) {
return null;
}

// The `data` property is a shorthand for sending a JSON body.
if ( data ) {
body = JSON.stringify( data );
headers[ 'Content-Type' ] = 'application/json';
return response.json ? response.json() : Promise.reject( response );
}

const responsePromise = window.fetch(
url || path,
{
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers,
}
);
const checkStatus = ( response ) => {
if ( response.status >= 200 && response.status < 300 ) {
return response;
}
return response;
};

throw response;
};
return responsePromise
.then( checkStatus )
.then( parseResponse )
.catch( ( response ) => {
if ( ! parse ) {
throw response;
}

const parseResponse = ( response ) => {
if ( parse ) {
if ( response.status === 204 ) {
return null;
}
const invalidJsonError = {
code: 'invalid_json',
message: __( 'The response is not a valid JSON response.' ),
};

return response.json ? response.json() : Promise.reject( response );
if ( ! response || ! response.json ) {
throw invalidJsonError;
}

return response;
};

return responsePromise
.then( checkStatus )
.then( parseResponse )
.catch( ( response ) => {
if ( ! parse ) {
throw response;
}

const invalidJsonError = {
code: 'invalid_json',
message: __( 'The response is not a valid JSON response.' ),
};

if ( ! response || ! response.json ) {
return response.json()
.catch( () => {
throw invalidJsonError;
}

return response.json()
.catch( () => {
throw invalidJsonError;
} )
.then( ( error ) => {
const unknownError = {
code: 'unknown_error',
message: __( 'An unknown error occurred.' ),
};

throw error || unknownError;
} );
} );
};
} )
.then( ( error ) => {
const unknownError = {
code: 'unknown_error',
message: __( 'An unknown error occurred.' ),
};

throw error || unknownError;
} );
} );
};

let fetchHandler = defaultFetchHandler;

/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {Function} newFetchHandler The new fetch handler
*/
function setFetchHandler( newFetchHandler ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this file was already lacking so JSDocs, but maybe a good time to start adding those.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in e2dc3d3

fetchHandler = newFetchHandler;
}

function apiFetch( options ) {
const steps = [ ...middlewares, fetchHandler ];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for updating this code here. It is now clear that fetchHandler is something unrelated to middlewares.


const createRunStep = ( index ) => ( workingOptions ) => {
const step = steps[ index ];
if ( index === steps.length - 1 ) {
return step( workingOptions );
}

const steps = [
raw,
fetchAllMiddleware,
httpV1Middleware,
namespaceEndpointMiddleware,
userLocaleMiddleware,
...middlewares,
].reverse();

const runMiddleware = ( index ) => ( nextOptions ) => {
const nextMiddleware = steps[ index ];
const next = runMiddleware( index + 1 );
return nextMiddleware( nextOptions, next );
const next = createRunStep( index + 1 );
return step( workingOptions, next );
};

return runMiddleware( 0 )( options );
return createRunStep( 0 )( options );
}

apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;

apiFetch.createNonceMiddleware = createNonceMiddleware;
apiFetch.createPreloadingMiddleware = createPreloadingMiddleware;
Expand Down
34 changes: 34 additions & 0 deletions packages/api-fetch/src/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,38 @@ describe( 'apiFetch', () => {
} );
} );
} );

it( 'should not use the default fetch handler when using a custom fetch handler', () => {
const customFetchHandler = jest.fn();

apiFetch.setFetchHandler( customFetchHandler );

apiFetch( { path: '/random' } );

expect( window.fetch ).not.toHaveBeenCalled();

expect( customFetchHandler ).toHaveBeenCalledWith( {
path: '/random?_locale=user',
} );
} );

it( 'should run the last-registered user-defined middleware first', () => {
// This could potentially impact other tests in that a lingering
// middleware is left. For the purposes of this test, it is sufficient
// to ensure that the last-registered middleware receives the original
// options object. It also assumes that some built-in middleware would
// either mutate or clone the original options if the extra middleware
// had been pushed to the stack.
expect.assertions( 1 );

const expectedOptions = {};

apiFetch.use( ( actualOptions, next ) => {
expect( actualOptions ).toBe( expectedOptions );

return next( actualOptions );
} );

apiFetch( expectedOptions );
} );
} );