用于调用 API 的 Redux 中间件。
Redux middleware for calling an API.
This middleware receives Redux Standard API-calling Actions (RSAAs) and dispatches Flux Standard Actions (FSAs) to the next middleware.
RSAAs are identified by the presence of an [RSAA] property, where RSAA is a String constant defined in, and exported by redux-api-middleware. They contain information describing an API call and three different types of FSAs, known as the request, success and failure FSAs.
The following is a minimal RSAA action:
import { createAction } from `redux-api-middleware`;
createAction({
endpoint: 'http://www.example.com/api/users',
method: 'GET',
types: ['REQUEST', 'SUCCESS', 'FAILURE']
})
Upon receiving this action, redux-api-middleware will
check that it is indeed a valid RSAA action;
dispatch the following request FSA to the next middleware;
{
type: 'REQUEST'
}
make a GET request to http://www.example.com/api/users;
if the request is successful, dispatch the following success FSA to the next middleware;
{
type: 'SUCCESS',
payload: {
users: [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
]
}
}
if the request is unsuccessful, dispatch the following failure FSA to the next middleware.
{
type: 'FAILURE',
payload: error // An ApiError object
error: true
}
We have tiptoed around error-handling issues here. For a thorough walkthrough of the redux-api-middleware lifecycle, see Lifecycle below.
See the 2.0 Release Notes, and Upgrading from v1.0.x for details on upgrading.
See the 3.0 Release Notes, and Upgrading from v2.0.x for details on upgrading.
redux-api-middleware is available on npm.
$ npm install redux-api-middleware --save
To use it, wrap the standard Redux store with it. Here is an example setup. For more information (for example, on how to add several middlewares), consult the Redux documentation.
Note: redux-api-middleware depends on a global Fetch being available, and may require a polyfill for your runtime environment(s).
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import reducers from './reducers';
const reducer = combineReducers(reducers);
const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);
export default function configureStore(initialState) {
return createStoreWithMiddleware(reducer, initialState);
}
const store = configureStore(initialState);
You can create an API call by creating an action using createAction and passing the following options to it.
endpoint (Required)The URL endpoint for the API call.
It is usually a string, be it a plain old one or an ES2015 template string. It may also be a function taking the state of your Redux store as its argument, and returning such a string.
method (Required)The HTTP method for the API call.
It must be one of the strings GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS, in any mixture of lowercase and uppercase letters.
bodyThe body of the API call.
redux-api-middleware uses the Fetch API to make the API call. body should hence be a valid body according to the fetch specification. In most cases, this will be a JSON-encoded string or a FormData object.
It may also be a function taking the state of your Redux store as its argument, and returning a body as described above.
headersThe HTTP headers for the API call.
It is usually an object, with the keys specifying the header names and the values containing their content. For example, you can let the server know your call contains a JSON-encoded string body in the following way.
createAction({
// ...
headers: { 'Content-Type': 'application/json' }
// ...
})
It may also be a function taking the state of your Redux store as its argument, and returning an object of headers as above.
optionsThe fetch options for the API call. What options are available depends on what fetch implementation is in use. See MDN fetch or node-fetch for more information.
It is usually an object with the options keys/values. For example, you can specify a network timeout for node.js code in the following way.
createAction({
// ...
options: { timeout: 3000 }
// ...
})
It may also be a function taking the state of your Redux store as its argument, and returning an object of options as above.
credentialsWhether or not to send cookies with the API call.
It must be one of the following strings:
omit is the default, and does not send any cookies;same-origin only sends cookies for the current domain;include always send cookies, even for cross-origin calls.fetchA custom Fetch implementation, useful for intercepting the fetch request to customize the response status, modify the response payload or skip the request altogether and provide a cached response instead.
If provided, the fetch option must be a function that conforms to the Fetch API. Otherwise, the global fetch will be used.
Examples:
Modify a response payload and status…
Modify a response status based on response jsoncreateAction({
// ...
fetch: async (...args) => {
const res = await fetch(...args);
const returnRes = res.clone(); // faster then above example with JSON.stringify
const json = await res.json(); // we need json just to check status
returnRes.status = json.error ? 500 : 200;
return returnRes;
}
// ...
})
Skip the request in favor of a cached responsecreateAction({
// ...
fetch: async (...args) => {
const cached = await getCache('someKey');
if (cached) {
// where `cached` is a JSON string: '{"foo": "bar"}'
return new Response(cached,
{
status: 200,
headers: {
'Content-Type': 'application/json'
}
}
);
}
// Fetch as usual if not cached
return fetch(...args);
}
// ...
})
In some cases, the data you would like to fetch from the server may already be cached in your Redux store. Or you may decide that the current user does not have the necessary permissions to make some request.
You can tell redux-api-middleware to not make the API call through bailout property. If the value is true, the RSAA will die here, and no FSA will be passed on to the next middleware.
A more useful possibility is to give bailout a function. At runtime, it will be passed the state of your Redux store as its only argument, if the return value of the function is true, the API call will not be made.
The types property controls the output of redux-api-middleware. The simplest form it can take is an array of length 3 consisting of string constants (or symbols), as in our example above. This results in the default behavior we now describe.
When redux-api-middleware receives an action, it first checks whether it has an [RSAA] property. If it does not, it was clearly not intended for processing with redux-api-middleware, and so it is unceremoniously passed on to the next middleware.
It is now time to validate the action against the RSAA definition. If there are any validation errors, a request FSA will be dispatched (if at all possible) with the following properties:
type: the string constant in the first position of the types array;payload: an InvalidRSAA object containing a list of said validation errors;error: true. redux-api-middleware will perform no further operations. In particular, no API call will be made, and the incoming RSAA will die here.
redux-api-middleware is sure it has received a valid RSAA, it will try making the API call. If everything is alright, a request FSA will be dispatched with the following property:type: the string constant in the first position of the types arr