├── .eslintrc
├── .gitignore
├── .size-limit
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── babel.config.js
├── jest.config.js
├── package-lock.json
├── package.json
├── rollup.config.js
├── src
├── RSAA.js
├── __snapshots__
│ ├── errors.test.js.snap
│ ├── middleware.test.js.snap
│ ├── util.test.js.snap
│ └── validation.test.js.snap
├── errors.js
├── errors.test.js
├── index.js
├── middleware.js
├── middleware.test.js
├── util.js
├── util.test.js
├── validation.js
└── validation.test.js
└── test
└── setupJest.js
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "plugins": [
3 | "prettier",
4 | "jest"
5 | ],
6 | "extends": ["plugin:jest/recommended"],
7 | "env": {
8 | "browser": true,
9 | "es6": true,
10 | "jest/globals": true
11 | },
12 | "parserOptions": {
13 | "ecmaVersion": 2018,
14 | "sourceType": "module"
15 | },
16 | "root": true,
17 | "rules": {
18 | "no-underscore-dangle": 0,
19 | "strict": [2, "global"],
20 | "eqeqeq": [2, "smart"],
21 | "no-undef": 2,
22 | "no-console": 1,
23 | "no-nested-ternary": 2,
24 | "jest/expect-expect": 0,
25 | "prettier/prettier": [
26 | "error",
27 | {
28 | "singleQuote": true
29 | }
30 | ]
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.log
3 | lib
4 | es
5 | coverage
6 | .nyc_output
7 | .idea
8 | .DS_Store
9 |
--------------------------------------------------------------------------------
/.size-limit:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "lib/index.cjs.js (min)",
4 | "path": "lib/index.cjs.js",
5 | "limit": "10 KB",
6 | "gzip": false
7 | },
8 | {
9 | "name": "lib/index.cjs.js (min + gzip)",
10 | "path": "lib/index.cjs.js",
11 | "limit": "4 KB"
12 | },
13 | {
14 | "name": "lib/index.umd.js (min)",
15 | "path": "lib/index.umd.js",
16 | "limit": "31 KB",
17 | "gzip": false
18 | },
19 | {
20 | "name": "lib/index.umd.js (min + gzip)",
21 | "path": "lib/index.umd.js",
22 | "limit": "12 KB"
23 | }
24 | ]
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "node"
4 | - "lts/*"
5 | cache:
6 | directories:
7 | - "node_modules"
8 | script:
9 | - npm run cover
10 | after_success:
11 | - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
12 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at michael@nason.us. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Prerequisites
2 |
3 | [Node.js](http://nodejs.org/) >= v8 must be installed.
4 |
5 | ## Installation
6 |
7 | - Running `npm install` in the module's root directory will install everything you need for development.
8 |
9 | ## Running Tests
10 |
11 | - `npm test` will run the tests once.
12 |
13 | ## Building
14 |
15 | - `npm run build` will build the module.
16 |
17 | - `npm run clean` will delete built resources.
18 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Alberto Garcia-Raboso
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | redux-api-middleware
2 | ====================
3 | [](https://npm.im/redux-api-middleware) [](https://npm.im/redux-api-middleware) [](https://travis-ci.org/agraboso/redux-api-middleware) [](https://coveralls.io/github/agraboso/redux-api-middleware?branch=master) [](https://bundlephobia.com/result?p=redux-api-middleware)
4 |
5 | [Redux middleware](https://redux.js.org/docs/advanced/Middleware.html) for calling an API.
6 |
7 | This middleware receives [*Redux Standard API-calling Actions*](#redux-standard-api-calling-actions) (RSAAs) and dispatches [*Flux Standard Actions*](#flux-standard-actions) (FSAs) to the next middleware.
8 |
9 | RSAAs are identified by the presence of an `[RSAA]` property, where [`RSAA`](#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.
10 |
11 | -------------------
12 |
13 | ## Table of contents
14 |
15 |
16 |
17 |
18 |
19 | - [Introduction](#introduction)
20 | - [Breaking Changes in 2.0 Release](#breaking-changes-in-20-release)
21 | - [Breaking Changes in 3.0 Release](#breaking-changes-in-30-release)
22 | - [Installation](#installation)
23 | - [configureStore.js](#configurestorejs)
24 | - [app.js](#appjs)
25 | - [Usage](#usage)
26 | - [Defining the API call](#defining-the-api-call)
27 | - [`endpoint`](#endpoint-required)
28 | - [`method`](#method-required)
29 | - [`body`](#body)
30 | - [`headers`](#headers)
31 | - [`options`](#options)
32 | - [`credentials`](#credentials)
33 | - [`fetch`](#fetch)
34 | - [Bailing out](#bailing-out)
35 | - [Lifecycle](#lifecycle)
36 | - [Customizing the dispatched FSAs](#customizing-the-dispatched-fsas)
37 | - [Dispatching Thunks](#dispatching-thunks)
38 | - [Testing](#testing)
39 | - [Reference](#reference)
40 | - [*Request* type descriptors](#request-type-descriptors)
41 | - [*Success* type descriptors](#success-type-descriptors)
42 | - [*Failure* type descriptors](#failure-type-descriptors)
43 | - [Exports](#exports)
44 | - [`createAction`](#createactionapicall)
45 | - [`RSAA`](#rsaa)
46 | - [`apiMiddleware`](#apimiddleware)
47 | - [`createMiddleware(options)`](#createmiddlewareoptions)
48 | - [`isRSAA(action)`](#isrsaaaction)
49 | - [`validateRSAA(action)`](#validatersaaaction)
50 | - [`isValidRSAA(action)`](#isvalidrsaaaction)
51 | - [`InvalidRSAA`](#invalidrsaa)
52 | - [`InternalError`](#internalerror)
53 | - [`RequestError`](#requesterror)
54 | - [`ApiError`](#apierror)
55 | - [`getJSON(res)`](#getjsonres)
56 | - [Flux Standard Actions](#flux-standard-actions)
57 | - [`type`](#type)
58 | - [`payload`](#payload)
59 | - [`error`](#error)
60 | - [`meta`](#meta)
61 | - [Redux Standard API-calling Actions](#redux-standard-api-calling-actions)
62 | - [`[RSAA]`](#rsaa)
63 | - [`endpoint`](#endpoint-1)
64 | - [`method`](#method-1)
65 | - [`body`](#body-1)
66 | - [`headers`](#headers-1)
67 | - [`options`](#options-1)
68 | - [`credentials`](#credentials-1)
69 | - [`bailout`](#bailout)
70 | - [`fetch`](#fetch-1)
71 | - [`ok`](#ok)
72 | - [`types`](#types)
73 | - [Type descriptors](#type-descriptors)
74 | - [History](#history)
75 | - [Tests](#tests)
76 | - [Upgrading from v1.0.x](#upgrading-from-v10x)
77 | - [Upgrading from v2.0.x](#upgrading-from-v20x)
78 | - [License](#license)
79 | - [Projects using redux-api-middleware](#projects-using-redux-api-middleware)
80 | - [Acknowledgements](#acknowledgements)
81 |
82 |
83 |
84 | ## Introduction
85 |
86 | The following is a minimal RSAA action:
87 |
88 | ```js
89 | import { createAction } from `redux-api-middleware`;
90 |
91 | createAction({
92 | endpoint: 'http://www.example.com/api/users',
93 | method: 'GET',
94 | types: ['REQUEST', 'SUCCESS', 'FAILURE']
95 | })
96 | ```
97 |
98 | Upon receiving this action, `redux-api-middleware` will
99 |
100 | 1. check that it is indeed a valid RSAA action;
101 | 2. dispatch the following *request* FSA to the next middleware;
102 |
103 | ```js
104 | {
105 | type: 'REQUEST'
106 | }
107 | ```
108 |
109 | 3. make a GET request to `http://www.example.com/api/users`;
110 | 4. if the request is successful, dispatch the following *success* FSA to the next middleware;
111 |
112 | ```js
113 | {
114 | type: 'SUCCESS',
115 | payload: {
116 | users: [
117 | { id: 1, name: 'John Doe' },
118 | { id: 2, name: 'Jane Doe' },
119 | ]
120 | }
121 | }
122 | ```
123 |
124 | 5. if the request is unsuccessful, dispatch the following *failure* FSA to the next middleware.
125 |
126 | ```js
127 | {
128 | type: 'FAILURE',
129 | payload: error // An ApiError object
130 | error: true
131 | }
132 | ```
133 |
134 | We have tiptoed around error-handling issues here. For a thorough walkthrough of the `redux-api-middleware` lifecycle, see [Lifecycle](#lifecycle) below.
135 |
136 | ### Breaking Changes in 2.0 Release
137 |
138 | See the [2.0 Release Notes](https://github.com/agraboso/redux-api-middleware/releases/tag/v2.0.0), and [Upgrading from v1.0.x](#upgrading-from-v10x) for details on upgrading.
139 |
140 | ### Breaking Changes in 3.0 Release
141 |
142 | See the [3.0 Release Notes](https://github.com/agraboso/redux-api-middleware/releases/tag/v3.0.0), and [Upgrading from v2.0.x](#upgrading-from-v20x) for details on upgrading.
143 |
144 | ## Installation
145 |
146 | `redux-api-middleware` is available on [npm](https://www.npmjs.com/package/redux-api-middleware).
147 |
148 | ```
149 | $ npm install redux-api-middleware --save
150 | ```
151 |
152 | 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](http://redux.js.org).
153 |
154 | Note: `redux-api-middleware` depends on a [global Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) being available, and may require a polyfill for your runtime environment(s).
155 |
156 | #### configureStore.js
157 |
158 | ```js
159 | import { createStore, applyMiddleware, combineReducers } from 'redux';
160 | import { apiMiddleware } from 'redux-api-middleware';
161 | import reducers from './reducers';
162 |
163 | const reducer = combineReducers(reducers);
164 | const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);
165 |
166 | export default function configureStore(initialState) {
167 | return createStoreWithMiddleware(reducer, initialState);
168 | }
169 | ```
170 |
171 | #### app.js
172 |
173 | ```js
174 | const store = configureStore(initialState);
175 | ```
176 |
177 | ## Usage
178 |
179 | ### Defining the API call
180 |
181 | You can create an API call by creating an action using `createAction` and passing the following options to it.
182 |
183 | #### `endpoint` (Required)
184 |
185 | The URL endpoint for the API call.
186 |
187 | 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.
188 |
189 | #### `method` (Required)
190 |
191 | The HTTP method for the API call.
192 |
193 | It must be one of the strings `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`, in any mixture of lowercase and uppercase letters.
194 |
195 | #### `body`
196 |
197 | The body of the API call.
198 |
199 | `redux-api-middleware` uses the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make the API call. `body` should hence be a valid body according to the [fetch specification](https://fetch.spec.whatwg.org). In most cases, this will be a JSON-encoded string or a [`FormData`](https://developer.mozilla.org/en/docs/Web/API/FormData) object.
200 |
201 | It may also be a function taking the state of your Redux store as its argument, and returning a body as described above.
202 |
203 | #### `headers`
204 |
205 | The HTTP headers for the API call.
206 |
207 | 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.
208 |
209 | ```js
210 | createAction({
211 | // ...
212 | headers: { 'Content-Type': 'application/json' }
213 | // ...
214 | })
215 | ```
216 |
217 | It may also be a function taking the state of your Redux store as its argument, and returning an object of headers as above.
218 |
219 | #### `options`
220 |
221 | The fetch options for the API call. What options are available depends on what fetch implementation is in use. See [MDN fetch](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) or [node-fetch](https://github.com/bitinn/node-fetch#options) for more information.
222 |
223 | It is usually an object with the options keys/values. For example, you can specify a network timeout for node.js code
224 | in the following way.
225 |
226 | ```js
227 | createAction({
228 | // ...
229 | options: { timeout: 3000 }
230 | // ...
231 | })
232 | ```
233 |
234 | It may also be a function taking the state of your Redux store as its argument, and returning an object of options as above.
235 |
236 | #### `credentials`
237 |
238 | Whether or not to send cookies with the API call.
239 |
240 | It must be one of the following strings:
241 |
242 | - `omit` is the default, and does not send any cookies;
243 | - `same-origin` only sends cookies for the current domain;
244 | - `include` always send cookies, even for cross-origin calls.
245 |
246 | #### `fetch`
247 |
248 | A custom [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/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.
249 |
250 | If provided, the fetch option must be a function that conforms to the Fetch API. Otherwise, the global fetch will be used.
251 |
252 | **Examples:**
253 |
254 |
255 | Modify a response payload and status
256 |
257 | ```js
258 | createAction({
259 | // ...
260 | fetch: async (...args) => {
261 | // `fetch` args may be just a Request instance or [URI, options] (see Fetch API docs above)
262 | const res = await fetch(...args);
263 | const json = await res.json();
264 |
265 | return new Response(
266 | JSON.stringify({
267 | ...json,
268 | // Adding to the JSON response
269 | foo: 'bar'
270 | }),
271 | {
272 | // Custom success/error status based on an `error` key in the API response
273 | status: json.error ? 500 : 200,
274 | headers: {
275 | 'Content-Type': 'application/json'
276 | }
277 | }
278 | );
279 | }
280 | // ...
281 | })
282 | ```
283 |
284 |
285 |
286 | Modify a response status based on response json
287 |
288 | ```js
289 | createAction({
290 | // ...
291 | fetch: async (...args) => {
292 | const res = await fetch(...args);
293 | const returnRes = res.clone(); // faster then above example with JSON.stringify
294 | const json = await res.json(); // we need json just to check status
295 |
296 | returnRes.status = json.error ? 500 : 200;
297 |
298 | return returnRes;
299 | }
300 | // ...
301 | })
302 | ```
303 |
304 |
305 |
306 | Skip the request in favor of a cached response
307 |
308 | ```js
309 | createAction({
310 | // ...
311 | fetch: async (...args) => {
312 | const cached = await getCache('someKey');
313 |
314 | if (cached) {
315 | // where `cached` is a JSON string: '{"foo": "bar"}'
316 | return new Response(cached,
317 | {
318 | status: 200,
319 | headers: {
320 | 'Content-Type': 'application/json'
321 | }
322 | }
323 | );
324 | }
325 |
326 | // Fetch as usual if not cached
327 | return fetch(...args);
328 | }
329 | // ...
330 | })
331 | ```
332 |
333 |
334 | ### Bailing out
335 |
336 | 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.
337 |
338 | 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.
339 |
340 | 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.
341 |
342 | ### Lifecycle
343 |
344 | 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](#a-simple-example) above. This results in the default behavior we now describe.
345 |
346 | 1. 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.
347 |
348 | 2. It is now time to validate the action against the [RSAA definition](#redux-standard-api-calling-actions). If there are any validation errors, a *request* FSA will be dispatched (if at all possible) with the following properties:
349 | - `type`: the string constant in the first position of the `types` array;
350 | - `payload`: an [`InvalidRSAA`](#invalidrsaa) object containing a list of said validation errors;
351 | - `error: true`.
352 |
353 | `redux-api-middleware` will perform no further operations. In particular, no API call will be made, and the incoming RSAA will die here.
354 |
355 | 3. Now that `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:
356 | - `type`: the string constant in the first position of the `types` array.
357 |
358 | But errors may pop up at this stage, for several reasons:
359 | - `redux-api-middleware` has to call those of `bailout`, `endpoint`, `body`, `options` and `headers` that happen to be a function, which may throw an error;
360 | - `fetch` may throw an error: the RSAA definition is not strong enough to preclude that from happening (you may, for example, send in a `body` that is not valid according to the fetch specification — mind the SHOULDs in the [RSAA definition](#redux-standard-api-calling-actions));
361 | - a network failure occurs (the network is unreachable, the server responds with an error,...).
362 |
363 | If such an error occurs, a *failure* FSA will be dispatched containing the following properties:
364 | - `type`: the string constant in the last position of the `types` array;
365 | - `payload`: a [`RequestError`](#requesterror) object containing an error message;
366 | - `error: true`.
367 |
368 | 4. If `redux-api-middleware` receives a response from the server with a status code in the 200 range, a *success* FSA will be dispatched with the following properties:
369 | - `type`: the string constant in the second position of the `types` array;
370 | - `payload`: if the `Content-Type` header of the response is set to something JSONy (see [*Success* type descriptors](#success-type-descriptors) below), the parsed JSON response of the server, or undefined otherwise.
371 |
372 | If the status code of the response falls outside that 200 range, a *failure* FSA will dispatched instead, with the following properties:
373 | - `type`: the string constant in the third position of the `types` array;
374 | - `payload`: an [`ApiError`](#apierror) object containing the message `` `${status} - ${statusText}` ``;
375 | - `error: true`.
376 |
377 | ### Customizing the dispatched FSAs
378 |
379 | It is possible to customize the output of `redux-api-middleware` by replacing one or more of the string constants (or symbols) in `types` by a type descriptor.
380 |
381 | A *type descriptor* is a plain JavaScript object that will be used as a blueprint for the dispatched FSAs. As such, type descriptors must have a `type` property, intended to house the string constant or symbol specifying the `type` of the resulting FSAs.
382 |
383 | They may also have `payload` and `meta` properties, which may be of any type. Functions passed as `payload` and `meta` properties of type descriptors will be evaluated at runtime. The signature of these functions should be different depending on whether the type descriptor refers to *request*, *success* or *failure* FSAs — keep reading.
384 |
385 | If a custom `payload` and `meta` function throws an error, `redux-api-middleware` will dispatch an FSA with its `error` property set to `true`, and an `InternalError` object as its `payload`.
386 |
387 | A noteworthy feature of `redux-api-middleware` is that it accepts Promises (or function that return them) in `payload` and `meta` properties of type descriptors, and it will wait for them to resolve before dispatching the FSA — so no need to use anything like `redux-promise`.
388 |
389 | ### Dispatching Thunks
390 |
391 | You can use `redux-thunk` to compose effects, dispatch custom actions on success/error, and implement other types of complex behavior.
392 |
393 | See [the Redux docs on composition](https://github.com/reduxjs/redux-thunk#composition) for more in-depth information, or expand the example below.
394 |
395 |
396 | Example
397 |
398 | ```js
399 | export function patchAsyncExampleThunkChainedActionCreator(values) {
400 | return async (dispatch, getState) => {
401 | const actionResponse = await dispatch(createAction({
402 | endpoint: "...",
403 | method: "PATCH",
404 | body: JSON.stringify(values),
405 | headers: {
406 | "Accept": "application/json",
407 | "Content-Type": "application/json",
408 | },
409 | types: [PATCH, PATCH_SUCCESS, PATCH_FAILED]
410 | }));
411 |
412 | if (actionResponse.error) {
413 | // the last dispatched action has errored, break out of the promise chain.
414 | throw new Error("Promise flow received action error", actionResponse);
415 | }
416 |
417 | // you can EITHER return the above resolved promise (actionResponse) here...
418 | return actionResponse;
419 |
420 | // OR resolve another asyncAction here directly and pass the previous received payload value as argument...
421 | return await yourOtherAsyncAction(actionResponse.payload.foo);
422 | };
423 | }
424 | ```
425 |
426 |
427 | ### Testing
428 |
429 | To test `redux-api-middleware` calls inside our application, we can create a fetch mock in order to simulate the response of the call. The `fetch-mock` and `redux-mock-store`packages can be used for this purpose as shown in the following example:
430 |
431 | **actions/user.js**
432 |
433 | ```javascript
434 | export const USER_REQUEST = '@@user/USER_REQUEST'
435 | export const USER_SUCCESS = '@@user/USER_SUCCESS'
436 | export const USER_FAILURE = '@@user/USER_FAILURE'
437 |
438 | export const getUser = () => createAction({
439 | endpoint: 'https://hostname/api/users/',
440 | method: 'GET',
441 | headers: { 'Content-Type': 'application/json' },
442 | types: [
443 | USER_REQUEST,
444 | USER_SUCCESS,
445 | USER_FAILURE
446 | ]
447 | })
448 | ```
449 |
450 | **actions/user.test.js**
451 |
452 | ```javascript
453 | // This is a Jest test, fyi
454 |
455 | import configureMockStore from 'redux-mock-store'
456 | import { apiMiddleware } from 'redux-api-middleware'
457 | import thunk from 'redux-thunk'
458 | import fetchMock from 'fetch-mock'
459 |
460 | import {getUser} from './user'
461 |
462 | const middlewares = [ thunk, apiMiddleware ]
463 | const mockStore = configureMockStore(middlewares)
464 |
465 | describe('async user actions', () => {
466 | // If we have several tests in our test suit, we might want to
467 | // reset and restore the mocks after each test to avoid unexpected behaviors
468 | afterEach(() => {
469 | fetchMock.reset()
470 | fetchMock.restore()
471 | })
472 |
473 | it('should dispatch USER_SUCCESS when getUser is called', () => {
474 | // We create a mock store for our test data.
475 | const store = mockStore({})
476 |
477 | const body = {
478 | email: 'EMAIL',
479 | username: 'USERNAME'
480 | }
481 | // We build the mock for the fetch request.
482 | // beware that the url must match the action endpoint.
483 | fetchMock.getOnce(`https://hostname/api/users/`, {body: body, headers: {'content-type': 'application/json'}})
484 | // We are going to verify the response with the following actions
485 | const expectedActions = [
486 | {type: actions.USER_REQUEST},
487 | {type: actions.USER_SUCCESS, payload: body}
488 | ]
489 | return store.dispatch(actions.getUser()).then(() => {
490 | // Verify that all the actions in the store are the expected ones
491 | expect(store.getActions()).toEqual(expectedActions)
492 | })
493 | })
494 | })
495 | ```
496 |
497 | ## Reference
498 |
499 | ### *Request* type descriptors
500 |
501 | `payload` and `meta` functions will be passed the RSAA action itself and the state of your Redux store.
502 |
503 | For example, if you want your *request* FSA to have the URL endpoint of the API call in its `payload` property, you can model your RSAA on the following.
504 |
505 | ```js
506 | // Input RSAA
507 | createAction({
508 | endpoint: 'http://www.example.com/api/users',
509 | method: 'GET',
510 | types: [
511 | {
512 | type: 'REQUEST',
513 | payload: (action, state) => ({ endpoint: action.endpoint })
514 | },
515 | 'SUCCESS',
516 | 'FAILURE'
517 | ]
518 | })
519 |
520 | // Output request FSA
521 | {
522 | type: 'REQUEST',
523 | payload: { endpoint: 'http://www.example.com/api/users' }
524 | }
525 | ```
526 |
527 | If you do not need access to the action itself or the state of your Redux store, you may as well just use a static object. For example, if you want the `meta` property to contain a fixed message saying where in your application you're making the request, you can do this.
528 |
529 | ```js
530 | // Input RSAA
531 | createAction({
532 | endpoint: 'http://www.example.com/api/users',
533 | method: 'GET',
534 | types: [
535 | {
536 | type: 'REQUEST',
537 | meta: { source: 'userList' }
538 | },
539 | 'SUCCESS',
540 | 'FAILURE'
541 | ]
542 | })
543 |
544 | // Output request FSA
545 | {
546 | type: 'REQUEST',
547 | meta: { source: 'userList' }
548 | }
549 | ```
550 |
551 | By default, *request* FSAs will not contain `payload` and `meta` properties.
552 |
553 | Error *request* FSAs might need to obviate these custom settings though.
554 | - *Request* FSAs resulting from invalid RSAAs (step 2 in [Lifecycle](#lifecycle) above) cannot be customized. `redux-api-middleware` will try to dispatch an error *request* FSA, but it might not be able to (it may happen that the invalid RSAA does not contain a value that can be used as the *request* FSA `type` property, in which case `redux-api-middleware` will let the RSAA die silently).
555 | - *Request* FSAs resulting in request errors (step 3 in [Lifecycle](#lifecycle) above) will honor the user-provided `meta`, but will ignore the user-provided `payload`, which is reserved for the default error object.
556 |
557 | ### *Success* type descriptors
558 |
559 | `payload` and `meta` functions will be passed the RSAA action itself, the state of your Redux store, and the raw server response.
560 |
561 | For example, if you want to process the JSON response of the server using [`normalizr`](https://github.com/gaearon/normalizr), you can do it as follows.
562 |
563 | ```js
564 | import { Schema, arrayOf, normalize } from 'normalizr';
565 | const userSchema = new Schema('users');
566 |
567 | // Input RSAA
568 | createAction({
569 | endpoint: 'http://www.example.com/api/users',
570 | method: 'GET',
571 | types: [
572 | 'REQUEST',
573 | {
574 | type: 'SUCCESS',
575 | payload: (action, state, res) => {
576 | const contentType = res.headers.get('Content-Type');
577 | if (contentType && ~contentType.indexOf('json')) {
578 | // Just making sure res.json() does not raise an error
579 | return res.json().then(json => normalize(json, { users: arrayOf(userSchema) }));
580 | }
581 | }
582 | },
583 | 'FAILURE'
584 | ]
585 | })
586 |
587 | // Output success FSA
588 | {
589 | type: 'SUCCESS',
590 | payload: {
591 | result: [1, 2],
592 | entities: {
593 | users: {
594 | 1: {
595 | id: 1,
596 | name: 'John Doe'
597 | },
598 | 2: {
599 | id: 2,
600 | name: 'Jane Doe'
601 | }
602 | }
603 | }
604 | }
605 | }
606 | ```
607 |
608 | The above pattern of parsing the JSON body of the server response is probably quite common, so `redux-api-middleware` exports a utility function `getJSON` which allows for the above `payload` function to be written as
609 | ```js
610 | (action, state, res) =>
611 | getJSON(res)
612 | .then(json => normalize(json, { users: arrayOf(userSchema) }));
613 | ```
614 |
615 | By default, *success* FSAs will not contain a `meta` property, while their `payload` property will be evaluated from
616 | ```js
617 | (action, state, res) => getJSON(res)
618 | ```
619 |
620 | ### *Failure* type descriptors
621 |
622 | `payload` and `meta` functions will be passed the RSAA action itself, the state of your Redux store, and the raw server response — exactly as for *success* type descriptors. The `error` property of dispatched *failure* FSAs will always be set to `true`.
623 |
624 | For example, if you want the status code and status message of a unsuccessful API call in the `meta` property of your *failure* FSA, do the following.
625 |
626 | ```js
627 | createAction({
628 | endpoint: 'http://www.example.com/api/users/1',
629 | method: 'GET',
630 | types: [
631 | 'REQUEST',
632 | 'SUCCESS',
633 | {
634 | type: 'FAILURE',
635 | meta: (action, state, res) => {
636 | if (res) {
637 | return {
638 | status: res.status,
639 | statusText: res.statusText
640 | };
641 | } else {
642 | return {
643 | status: 'Network request failed'
644 | }
645 | }
646 | }
647 | }
648 | ]
649 | })
650 | ```
651 |
652 | By default, *failure* FSAs will not contain a `meta` property, while their `payload` property will be evaluated from
653 | ```js
654 | (action, state, res) =>
655 | getJSON(res)
656 | .then(json => new ApiError(res.status, res.statusText, json))
657 | ```
658 |
659 |
660 | Note that *failure* FSAs dispatched due to fetch errors will not have a `res` argument into `meta` or `payload`. The `res` parameter will exist for completed requests that have resulted in errors, but not for failed requests.
661 |
662 | ### Exports
663 |
664 | The following objects are exported by `redux-api-middleware`.
665 |
666 | #### `createAction(apiCall)`
667 |
668 | Function used to create RSAA action. This is the preferred way to create a RSAA action.
669 |
670 | #### `RSAA`
671 |
672 | A JavaScript `String` whose presence as a key in an action signals that `redux-api-middleware` should process said action.
673 |
674 | #### `apiMiddleware`
675 |
676 | The Redux middleware itself.
677 |
678 | #### `createMiddleware(options)`
679 |
680 | A function that creates an `apiMiddleware` with custom options.
681 |
682 | The following `options` properties are used:
683 |
684 | - `fetch` - provide a `fetch` API compatible function here to use instead of the default `window.fetch`
685 | - `ok` - provide a function here to use as a status check in the RSAA flow instead of `(res) => res.ok`
686 |
687 | #### `isRSAA(action)`
688 |
689 | A function that returns `true` if `action` has an `[RSAA]` property, and `false` otherwise.
690 |
691 | #### `validateRSAA(action)`
692 |
693 | A function that validates `action` against the RSAA definition, returning an array of validation errors.
694 |
695 | #### `isValidRSAA(action)`
696 |
697 | A function that returns `true` if `action` conforms to the RSAA definition, and `false` otherwise. Internally, it simply checks the length of the array of validation errors returned by `validateRSAA(action)`.
698 |
699 | #### `InvalidRSAA`
700 |
701 | An error class extending the native `Error` object. Its constructor takes an array of validation errors as its only argument.
702 |
703 | `InvalidRSAA` objects have three properties:
704 |
705 | - `name: 'InvalidRSAA'`;
706 | - `validationErrors`: the argument of the call to its constructor; and
707 | - `message: 'Invalid RSAA'`.
708 |
709 | #### `InternalError`
710 |
711 | An error class extending the native `Error` object. Its constructor takes a string, intended to contain an error message.
712 |
713 | `InternalError` objects have two properties:
714 |
715 | - `name: 'InternalError'`;
716 | - `message`: the argument of the call to its constructor.
717 |
718 | #### `RequestError`
719 |
720 | An error class extending the native `Error` object. Its constructor takes a string, intended to contain an error message.
721 |
722 | `RequestError` objects have two properties:
723 |
724 | - `name: 'RequestError'`;
725 | - `message`: the argument of the call to its constructor.
726 |
727 | #### `ApiError`
728 |
729 | An error class extending the native `Error` object. Its constructor takes three arguments:
730 |
731 | - a status code,
732 | - a status text, and
733 | - a further object, intended for a possible JSON response from the server.
734 |
735 | `ApiError` objects have five properties:
736 |
737 | - `name: 'ApiError'`;
738 | - `status`: the first argument of the call to its constructor;
739 | - `statusText`: the second argument of the call to its constructor;
740 | - `response`: to the third argument of the call to its constructor; and
741 | - `` message : `${status} - ${statusText}` ``.
742 |
743 | #### `getJSON(res)`
744 |
745 | A function taking a response object as its only argument. If the response object contains a JSONy `Content-Type`, it returns a promise resolving to its JSON body. Otherwise, it returns a promise resolving to undefined.
746 |
747 | ### Flux Standard Actions
748 |
749 | For convenience, we recall here the definition of a [*Flux Standard Action*](https://github.com/acdlite/flux-standard-action).
750 |
751 | An action MUST
752 |
753 | - be a plain JavaScript object,
754 | - have a `type` property.
755 |
756 | An action MAY
757 |
758 | - have an `error` property,
759 | - have a `payload` property,
760 | - have a `meta` property.
761 |
762 | An action MUST NOT
763 |
764 | - include properties other than `type`, `payload`, `error` and `meta`.
765 |
766 | #### `type`
767 |
768 | The `type` of an action identifies to the consumer the nature of the action that has occurred. Two actions with the same `type` MUST be strictly equivalent (using `===`). By convention, `type` is usually a string constant or a `Symbol`.
769 |
770 | #### `payload`
771 |
772 | The optional `payload` property MAY be any type of value. It represents the payload of the action. Any information about the action that is not the `type` or status of the action should be part of the `payload` field.
773 |
774 | By convention, if `error` is true, the `payload` SHOULD be an error object. This is akin to rejecting a Promise with an error object.
775 |
776 | #### `error`
777 |
778 | The optional `error` property MAY be set to `true` if the action represents an error.
779 |
780 | An action whose `error` is true is analogous to a rejected Promise. By convention, the `payload` SHOULD be an error object.
781 |
782 | If `error` has any other value besides `true`, including `undefined` and `null`, the action MUST NOT be interpreted as an error.
783 |
784 | #### `meta`
785 |
786 | The optional `meta` property MAY be any type of value. It is intended for any extra information that is not part of the payload.
787 |
788 | ### Redux Standard API-calling Actions
789 |
790 | The definition of a *Redux Standard API-calling Action* below is the one used to validate RSAA actions. As explained in [Lifecycle](#lifecycle),
791 | - actions without an `[RSAA]` property will be passed to the next middleware without any modifications;
792 | - actions with an `[RSAA]` property that fail validation will result in an error *request* FSA.
793 |
794 | A *Redux Standard API-calling Action* MUST
795 |
796 | - be a plain JavaScript object,
797 | - have an `[RSAA]` property.
798 |
799 | A *Redux Standard API-calling Action* MAY
800 |
801 | - include properties other than `[RSAA]` (but will be ignored by redux-api-middleware).
802 |
803 | #### Action object
804 |
805 | The `[RSAA]` property MUST
806 |
807 | - be a plain JavaScript Object,
808 | - have an `endpoint` property,
809 | - have a `method` property,
810 | - have a `types` property.
811 |
812 | The `[RSAA]` property MAY
813 |
814 | - have a `body` property,
815 | - have a `headers` property,
816 | - have an `options` property,
817 | - have a `credentials` property,
818 | - have a `bailout` property,
819 | - have a `fetch` property,
820 | - have an `ok` property.
821 |
822 | The `[RSAA]` property MUST NOT
823 |
824 | - include properties other than `endpoint`, `method`, `types`, `body`, `headers`, `options`, `credentials`, `bailout`, `fetch` and `ok`.
825 |
826 | #### `endpoint`
827 |
828 | The `endpoint` property MUST be a string or a function. In the second case, the function SHOULD return a string.
829 |
830 | #### `method`
831 |
832 | The `method` property MUST be one of the strings `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`, in any mixture of lowercase and uppercase letters.
833 |
834 | #### `body`
835 |
836 | The optional `body` property SHOULD be a valid body according to the [fetch specification](https://fetch.spec.whatwg.org), or a function. In the second case, the function SHOULD return a valid body.
837 |
838 | #### `headers`
839 |
840 | The optional `headers` property MUST be a plain JavaScript object or a function. In the second case, the function SHOULD return a plain JavaScript object.
841 |
842 | #### `options`
843 |
844 | The optional `options` property MUST be a plain JavaScript object or a function. In the second case, the function SHOULD return a plain JavaScript object.
845 | The options object can contain any options supported by the effective fetch implementation.
846 | See [MDN fetch](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) or [node-fetch](https://github.com/bitinn/node-fetch#options).
847 |
848 | #### `credentials`
849 |
850 | The optional `credentials` property MUST be one of the strings `omit`, `same-origin` or `include`.
851 |
852 | #### `bailout`
853 |
854 | The optional `bailout` property MUST be a boolean or a function.
855 |
856 | #### `fetch`
857 |
858 | The optional `fetch` property MUST be a function that conforms to the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
859 |
860 | #### `ok`
861 |
862 | The optional `ok` property MUST be a function that accepts a response object and returns a boolean indicating if the request is a success or failure
863 |
864 | #### `types`
865 |
866 | The `types` property MUST be an array of length 3. Each element of the array MUST be a string, a `Symbol`, or a type descriptor.
867 |
868 | #### Type descriptors
869 |
870 | A type descriptor MUST
871 |
872 | - be a plain JavaScript object,
873 | - have a `type` property, which MUST be a string or a `Symbol`.
874 |
875 | A type descriptor MAY
876 |
877 | - have a `payload` property, which MAY be of any type,
878 | - have a `meta` property, which MAY be of any type.
879 |
880 | A type descriptor MUST NOT
881 |
882 | - have properties other than `type`, `payload` and `meta`.
883 |
884 | ## History
885 |
886 | TODO
887 |
888 | ## Tests
889 |
890 | ```
891 | $ npm install && npm test
892 | ```
893 |
894 | ## Upgrading from v1.0.x
895 |
896 | - The `CALL_API` symbol is replaced with the `RSAA` string as the top-level RSAA action key. `CALL_API` is aliased to the new value as of 2.0, but this will ultimately be deprecated.
897 | - `redux-api-middleware` no longer brings its own `fetch` implementation and depends on a global `fetch` to be provided in the runtime
898 | - A new `options` config is added to pass your `fetch` implementation extra options other than `method`, `headers`, `body` and `credentials`
899 | - `apiMiddleware` no longer returns a promise on actions without [RSAA]
900 |
901 | ## Upgrading from v2.0.x
902 |
903 | - The `CALL_API` alias has been removed
904 | - Error handling around failed fetches has been updated ([#175](https://github.com/agraboso/redux-api-middleware/pull/175))
905 | - Previously, a failed `fetch` would dispatch a `REQUEST` FSA followed by another `REQUEST` FSA with an error flag
906 | - Now, a failed `fetch` will dispatch a `REQUEST` FSA followed by a `FAILURE` FSA
907 |
908 | ## License
909 |
910 | MIT
911 |
912 | ## Projects using redux-api-middleware
913 |
914 | - [react-trebuchet](https://github.com/barrystaes/react-trebuchet/tree/test-bottledapi-apireduxmiddleware) (experimental/opinionated fork of react-slingshot for SPA frontends using REST JSON API backends)
915 |
916 | If your opensource project uses (or works with) `redux-api-middleware` we would be happy to list it here!
917 |
918 | ## Acknowledgements
919 |
920 | The code in this module was originally extracted from the [real-world](https://github.com/reduxjs/redux/blob/master/examples/real-world/src/middleware/api.js) example in the [redux](https://github.com/rackt/redux) repository, due to [Dan Abramov](https://github.com/gaearon). It has evolved thanks to issues filed by, and pull requests contributed by, other developers.
921 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = function (api) {
2 | const env = api.cache(() => process.env.NODE_ENV);
3 |
4 | const nodeTarget = env === 'test' ? 'current' : '8';
5 | const envModules = env === 'test' ? 'commonjs' : false;
6 |
7 | const presets = [
8 | [
9 | "@babel/preset-env", {
10 | modules: envModules,
11 | "useBuiltIns": "usage",
12 | "targets": {
13 | "node": nodeTarget
14 | },
15 | }
16 | ]
17 | ];
18 |
19 | const plugins = [];
20 |
21 | return {
22 | presets,
23 | plugins
24 | };
25 | }
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | verbose: !!process.env.CI,
3 | automock: false,
4 | resetMocks: true,
5 | restoreMocks: true,
6 | resetModules: true,
7 | setupFiles: [
8 | "./test/setupJest.js"
9 | ],
10 | moduleNameMapper: {
11 | "^redux-api-middleware$": process.env.TEST_LIB ? '..' : './index'
12 | }
13 | };
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "redux-api-middleware",
3 | "version": "3.2.1",
4 | "description": "Redux middleware for calling an API.",
5 | "main": "lib/index.cjs.js",
6 | "browser": "lib/index.umd.js",
7 | "module": "es/index.js",
8 | "sideEffects": false,
9 | "scripts": {
10 | "build": "babel src --out-dir es && rollup -c",
11 | "postbuild": "npm run size",
12 | "clean": "rimraf es lib coverage",
13 | "test": "cross-env NODE_ENV=test jest src es",
14 | "test:build": "cross-env TEST_LIB=true NODE_ENV=test jest src",
15 | "cover": "npm test -- --verbose --coverage --collectCoverageFrom \"src/**/*.js\"",
16 | "lint": "eslint src",
17 | "prepublishOnly": "npm run lint && npm test && npm run clean && npm run build && npm run test:build",
18 | "size": "size-limit"
19 | },
20 | "repository": "agraboso/redux-api-middleware",
21 | "homepage": "https://github.com/agraboso/redux-api-middleware",
22 | "keywords": [
23 | "redux",
24 | "api",
25 | "middleware",
26 | "redux-middleware",
27 | "flux"
28 | ],
29 | "author": {
30 | "name": "Alberto Garcia-Raboso",
31 | "email": "agraboso@gmail.com"
32 | },
33 | "license": "MIT",
34 | "dependencies": {},
35 | "devDependencies": {
36 | "@babel/cli": "^7.8.4",
37 | "@babel/core": "^7.8.7",
38 | "@babel/preset-env": "^7.8.7",
39 | "@rollup/plugin-commonjs": "^11.0.2",
40 | "@rollup/plugin-node-resolve": "^7.1.1",
41 | "@size-limit/preset-small-lib": "^4.4.0",
42 | "babel-core": "^7.0.0-bridge.0",
43 | "coveralls": "^3.0.9",
44 | "cross-env": "^7.0.2",
45 | "eslint": "^6.8.0",
46 | "eslint-plugin-jest": "^23.8.2",
47 | "eslint-plugin-prettier": "^3.1.2",
48 | "jest": "^23.6.0",
49 | "jest-fetch-mock": "^1.7.5",
50 | "prettier": "^1.19.1",
51 | "rimraf": "^2.7.1",
52 | "rollup": "^1.32.1",
53 | "rollup-plugin-babel": "^4.4.0",
54 | "size-limit": "^4.4.0"
55 | },
56 | "files": [
57 | "README.md",
58 | "LICENSE.md",
59 | "es",
60 | "lib"
61 | ]
62 | }
63 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import resolve from '@rollup/plugin-node-resolve';
2 | import commonjs from '@rollup/plugin-commonjs';
3 | import babel from 'rollup-plugin-babel';
4 | import pkg from './package.json';
5 |
6 | const pkgDeps = Object.keys(pkg.dependencies)
7 |
8 | export default [
9 | // browser-friendly UMD build
10 | {
11 | input: 'src/index.js',
12 | output: {
13 | file: pkg.browser,
14 | format: 'umd',
15 | name: 'ReduxApiMiddleware',
16 | },
17 | plugins: [
18 | resolve(),
19 | commonjs(),
20 | babel({
21 | exclude: ['node_modules/**'],
22 | presets: [
23 | [
24 | "@babel/preset-env", {
25 | modules: false,
26 | useBuiltIns: "usage"
27 | }
28 | ]
29 | ]
30 | })
31 | ]
32 | },
33 |
34 | // CommonJS (for Node)
35 | {
36 | input: 'src/index.js',
37 | output: {
38 | file: pkg.main,
39 | format: 'cjs',
40 | },
41 | external: pkgDeps,
42 | plugins: [
43 | babel({
44 | exclude: ['node_modules/**']
45 | })
46 | ]
47 | }
48 | ];
--------------------------------------------------------------------------------
/src/RSAA.js:
--------------------------------------------------------------------------------
1 | /**
2 | * String key that carries API call info interpreted by this Redux middleware.
3 | *
4 | * @constant {string}
5 | * @access public
6 | * @deprecated To be made private (implementation detail). Use `createAction` instead.
7 | * @default
8 | */
9 | const RSAA = '@@redux-api-middleware/RSAA';
10 |
11 | export default RSAA;
12 |
--------------------------------------------------------------------------------
/src/__snapshots__/errors.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`ApiError matches snapshot 1`] = `[ApiError: 404 - Not Found]`;
4 |
5 | exports[`ApiError matches snapshot: object.entries 1`] = `
6 | Array [
7 | Array [
8 | "name",
9 | "ApiError",
10 | ],
11 | Array [
12 | "status",
13 | 404,
14 | ],
15 | Array [
16 | "statusText",
17 | "Not Found",
18 | ],
19 | Array [
20 | "response",
21 | Object {
22 | "error": "Resource not found",
23 | },
24 | ],
25 | Array [
26 | "message",
27 | "404 - Not Found",
28 | ],
29 | ]
30 | `;
31 |
32 | exports[`InternalError matches snapshot 1`] = `[InternalError: error thrown in payload function]`;
33 |
34 | exports[`InternalError matches snapshot: object.entries 1`] = `
35 | Array [
36 | Array [
37 | "name",
38 | "InternalError",
39 | ],
40 | Array [
41 | "message",
42 | "error thrown in payload function",
43 | ],
44 | ]
45 | `;
46 |
47 | exports[`InvalidRSAA matches snapshot 1`] = `[InvalidRSAA: Invalid RSAA]`;
48 |
49 | exports[`InvalidRSAA matches snapshot: object.entries 1`] = `
50 | Array [
51 | Array [
52 | "name",
53 | "InvalidRSAA",
54 | ],
55 | Array [
56 | "message",
57 | "Invalid RSAA",
58 | ],
59 | Array [
60 | "validationErrors",
61 | Array [
62 | "validation error 1",
63 | "validation error 2",
64 | ],
65 | ],
66 | ]
67 | `;
68 |
69 | exports[`RequestError matches snapshot 1`] = `[RequestError: Network request failed]`;
70 |
71 | exports[`RequestError matches snapshot: object.entries 1`] = `
72 | Array [
73 | Array [
74 | "name",
75 | "RequestError",
76 | ],
77 | Array [
78 | "message",
79 | "Network request failed",
80 | ],
81 | ]
82 | `;
83 |
--------------------------------------------------------------------------------
/src/__snapshots__/middleware.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`#apiMiddleware must dispatch a failure FSA on an unsuccessful API call with a non-JSON response: fetch mock 1`] = `
4 | Object {
5 | "calls": Array [
6 | Array [
7 | "http://127.0.0.1/api/users/1",
8 | Object {
9 | "body": undefined,
10 | "credentials": undefined,
11 | "headers": Object {},
12 | "method": "GET",
13 | },
14 | ],
15 | ],
16 | "instances": Array [
17 | undefined,
18 | ],
19 | "invocationCallOrder": Any