Skip to content

Commit 5dbfe1c

Browse files
authored
Adds simplified object literal syntax (#4)
* Adds simplified object literal syntax * Refactors the 'handle' prefix in favor of the 'on' prefix * Adds examples and api descriptions to the docs * Adds HttpMiddlewareService api and simplified syntax documentation * Adds test with both middleware syntaxes
1 parent cae56a0 commit 5dbfe1c

File tree

16 files changed

+350
-181
lines changed

16 files changed

+350
-181
lines changed

.eslintrc.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ module.exports = {
1818
'no-duplicate-imports': 'error',
1919
// risk only exist with semi-colon auto insertion. Not our case.
2020
'no-plusplus': 'off',
21+
'no-param-reassign': 'off',
2122
'no-underscore-dangle': ['error', {
2223
'allowAfterSuper': true,
2324
'allowAfterThis': true,

docs/README.md

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,40 +11,34 @@ There are two classes exposed in this module:
1111

1212
It works with either the global axios or a local instance.
1313

14-
## Creating your middleware
14+
## Examples
1515

16-
Here's a simple example of a locale middleware who sets a language header on each AJAX request.
16+
All examples are written using ES6 syntax but you can definitely use this plugin with ES5 code, even directly in the browser.
1717

18-
```javascript
19-
import { HttpMiddleware } from 'axios-middleware';
18+
### Simplest use-case
2019

21-
export default class ErrorMiddleware extends HttpMiddleware {
22-
handleResponseError(error) {
23-
console.log("Handling:", error);
24-
}
25-
}
26-
```
20+
?> A common use-case would be to expose an instance of the service which consumes an _axios_ instance configured for an API. It's then possible to register middlewares for this API at different stages of the initialization process of an application.
2721

28-
## Using the service
29-
30-
Simplest use-case:
22+
The following example is using the [simplified syntax](simplified-syntax.md).
3123

3224
```javascript
3325
import axios from 'axios';
3426
import { HttpMiddlewareService } from 'axios-middleware';
35-
import i18n from './i18n';
36-
import { LocaleMiddleware, OtherMiddleware } from './middlewares';
3727

3828
// Create a new service instance
3929
const service = new HttpMiddlewareService(axios);
4030

4131
// Then register your middleware instances.
42-
service.register([
43-
new LocaleMiddleware(i18n),
44-
new OtherMiddleware()
45-
]);
32+
service.register({
33+
onRequest() {
34+
// handle the request
35+
},
36+
onResponseError(error) {
37+
// handle the response error
38+
}
39+
});
4640

4741
// We're good to go!
42+
export default { service };
4843
```
4944

50-
A common use-case would be to expose an instance of the service which consumes an _axios_ instance configured for an API. It's then possible to register middlewares for this API at different stages of the initialization process of an application.

docs/_navbar.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
- [Github](https://github.com/emileber/axios-middleware)
2-
- [npm](https://www.npmjs.com/package/axios-middleware)
2+
- [![npm version](https://badge.fury.io/js/axios-middleware.svg)](https://www.npmjs.com/package/axios-middleware)

docs/_sidebar.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
- Introduction
22
- [Getting started]()
33
- [Installation](installation.md)
4-
- [Examples](examples.md)
4+
- [Simplified syntax](simplified-syntax.md)
5+
6+
- API
7+
- [`HttpMiddleware`](api/HttpMiddleware.md)
8+
- [`HttpMiddlewareService`](api/HttpMiddlewareService.md)
9+
10+
- Examples
11+
- [Locale middleware](examples/locale-middleware.md)
12+
- [Service module](examples/service.md)
13+
- [ES5 usage](examples/es5.md)
14+
- [Browser usage](examples/browser.md)
515

616
- Ecosystem
717
- [Github](https://github.com/emileber/axios-middleware)

docs/api/HttpMiddleware.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# HttpMiddleware
2+
3+
?> This class is optional if you opt to use the [simplified syntax](simplified-syntax.md).
4+
5+
The base implementation to inherit when creating your custom implementation. **Any function is optional** and should be provided within a custom middleware only if needed.
6+
7+
## `constructor`
8+
9+
The constructor isn't used in the default middleware, leaving it totally available to the child classes. Very useful to pass any relevant services your middleware might need, like [the `i18n` service in our example](examples/locale-middleware.md).
10+
11+
## `onRequest(config)`
12+
13+
Receives the configuration objects before the request is made. Useful to add headers, query parameters, validate data, etc.
14+
15+
!> It must return the received `config` even if no changes were made to it.
16+
17+
## `onRequestError(error)`
18+
19+
No internet connection right now? You might end up in this function. Do what you need with the error.
20+
21+
## `onResponse(response)`
22+
23+
Parsing the response can be done here. Say all responses from your API are returned nested within a `_data` property?
24+
25+
```javascript
26+
onResponse(response) {
27+
return response._data;
28+
}
29+
```
30+
31+
!> The original `response` object or _a new one_ should be returned.
32+
33+
## `onResponseError(error)`
34+
35+
Not authenticated? Server problems? You might end up here. Do what you need with the error.

docs/api/HttpMiddlewareService.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# HttpMiddlewareService
2+
3+
This is the heart of this plugin module. It works by leveraging axios interceptors to call its middleware queue.
4+
5+
## `constructor(axios)`
6+
7+
You can pass an optional axios instance (the global one, or a local instance) on which to register the middlewares. If you don't pass an axios instance right away, you can use the `setHttp` method later on.
8+
9+
Even if no axios instance was passed, you can still register middlewares.
10+
11+
## `setHttp(axios)`
12+
13+
Sets or replaces the axios instance on which to intercept the requests and responses.
14+
15+
## `unsetHttp()`
16+
17+
Removes the registered interceptors on the axios instance, if any were set.
18+
19+
## `has(middleware)`
20+
21+
Returns `true` is the passed `middleware` instance is within the queue.
22+
23+
## `register(middlewares)`
24+
25+
Adds a middleware instance or an array of middlewares to the queue.
26+
27+
You can pass an `HttpMiddleware` instance or a simple object implementing only the functions you need (see the [simplified syntax](simplified-syntax.md)).
28+
29+
!> Throws an error if a middleware instance is already within the queue.
30+
31+
## `unregister(middleware)`
32+
33+
Removes a middleware instance from the queue.
34+
35+
## `reset()`
36+
37+
Empty the middleware queue.

docs/examples.md

Lines changed: 0 additions & 112 deletions
This file was deleted.

docs/examples/browser.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Usage in the browser
2+
3+
The _axios-middleware_ plugin is made to be easily used in the browser right away.
4+
5+
## Common usage
6+
7+
Just use the short middleware syntax to quickly define one-time use middleware.
8+
9+
```html
10+
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
11+
<script src="https://unpkg.com/axios-middleware/dist/axios-middleware.min.js"></script>
12+
<script>
13+
// Create a new service instance
14+
var service = new HttpMiddlewareService(axios);
15+
16+
// Then register your middleware instances.
17+
service.register({
18+
onRequest: function(config) {
19+
// handle the request
20+
},
21+
onResponseError(error) {
22+
// handle the response error
23+
}
24+
});
25+
</script>
26+
```
27+
28+
29+
## Advanced usage
30+
31+
A mix of the ES5 usage within a common namespacing pattern for an app.
32+
33+
Define your middlewares within a `Middleware.js` file.
34+
35+
```javascript
36+
// Middleware.js
37+
var app = app || {};
38+
39+
/**
40+
* Custom Middleware class
41+
*/
42+
app.MyMiddleware = (function(HttpMiddleware){
43+
function MyMiddleware() {
44+
// call the parent constructor
45+
HttpMiddleware.apply(this, arguments);
46+
}
47+
48+
var proto = MyMiddleware.prototype = Object.create(HttpMiddleware.prototype);
49+
50+
proto.constructor = MyMiddleware;
51+
proto.onRequest = function(config) {
52+
// handle the request
53+
};
54+
return MyMiddleware;
55+
})(AxiosMiddleware.HttpMiddleware);
56+
```
57+
58+
Then register these middlewares with a newly created `HttpMiddlewareService` instance.
59+
60+
```javascript
61+
// Service.js
62+
var app = app || {};
63+
64+
/**
65+
* Middleware Service
66+
*/
67+
app.MiddlewareService = (function(HttpMiddlewareService, MyMiddleware) {
68+
// Create a new service instance
69+
var service = new HttpMiddlewareService(axios);
70+
71+
// Then register your middleware instances.
72+
service.register(new MyMiddleware());
73+
74+
return service;
75+
})(AxiosMiddleware.HttpMiddlewareService, app.MyMiddleware);
76+
```
77+
78+
In this case, the order in which to import the JS files is important.
79+
80+
```html
81+
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
82+
<script src="https://unpkg.com/axios-middleware/dist/axios-middleware.min.js"></script>
83+
<script src="Middleware.js"></script>
84+
<script src="Service.js"></script>
85+
```
86+
87+
?> At that point, you may realise that it's a lot of files. You might want to think about using a bundler like [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/guide/en), or a simple concatenation pipeline with [grunt](https://gruntjs.com/) or [gulp](https://gulpjs.com/).

0 commit comments

Comments
 (0)