1
- ## We're going to create a new page that will contain a login form, if we're authenticated, the response will return a JWT, that we will use to call an API. If everythoi
1
+ ## We're going to create a new page that will contain a login form, if we're authenticated, the response will return a JWT, that we will use to call an API. If everything goes fine we well allow to access to server resources.
2
2
3
- * Lets start by creating a _ index.html_
3
+ * For this demo we will create a new project.
4
+
5
+ ```
6
+ npm init -y
7
+ ```
8
+
9
+ ```
10
+ npm i axios -S
11
+ ```
12
+
13
+ ```
14
+ npm i parcel -D
15
+ ```
16
+
17
+ * Lets start by creating _ index.html_ in root folder solution.
4
18
5
19
``` html
6
20
<!DOCTYPE html>
31
45
32
46
</html >
33
47
```
48
+
49
+ * All our solution code will be placed in __ src__ folder. Create this folder in root folder solution.
50
+
34
51
* Lets create the code to handle this _ form_ , first we're going to create a new entry in _ src/API/loginAPI.js_
35
52
36
53
``` javascript
@@ -41,53 +58,96 @@ export default ({username, password}) => (
41
58
);
42
59
```
43
60
44
- * Now it's time handle the UI code, but first we're going to create a new style of handling events, a way that allow us to retun _ promises _ , create _ src/asynApi.js _
61
+ * Now it's time handle the UI code, but first we're going to create a new style for handling events, we're going o create an event emitter. Create __ src/eventEmitter.js __
45
62
46
63
``` javascript
47
- export const submitButtonPromise = (event , targetId ) => (
48
- new Promise ((resolve , _ ) => {
49
- document .getElementById (targetId)
50
- .addEventListener (event , (evt ) => {
51
- evt .stopPropagation ();
52
- evt .preventDefault ();
53
- resolve ();
54
- });
55
- })
56
- );
64
+ const observer = () => {
65
+ const observers = [];
66
+ return {
67
+ subscribe (f ) {
68
+ observers .push (f);
69
+ },
70
+ unsubscibe (f ) {
71
+ observers = observers .filter ((subscriber ) => subscriber !== f);
72
+ },
73
+ notify (data ) {
74
+ observers .forEach ((observer ) => observer (data));
75
+ }
76
+ }
77
+ };
78
+
79
+ export const eventSubscription = (targetId ) => (event ) => {
80
+ const eventTarget = document .getElementById (targetId);
81
+
82
+ let obs = observer ();
83
+
84
+ eventTarget .addEventListener (event , (evt ) => {
85
+ evt .stopPropagation ();
86
+ evt .preventDefault ();
87
+ obs .notify (evt);
88
+ });
89
+
90
+ return obs;
91
+ }
92
+
57
93
```
58
94
59
95
* Now we can create _ src/app.js_
60
96
61
97
``` javascript
62
- // import { appendElement, createList } from './view/uiBuilder';
63
- import { submitButtonPromise } from ' ./asyncApi' ;
98
+ import { eventSubscription } from ' ./eventEmitter' ;
64
99
import login from ' ./API/loginAPI' ;
65
100
66
-
67
101
const readCredentials = () => {
68
102
const username = document .getElementById (' username' ).value ;
69
103
const password = document .getElementById (' password' ).value ;
70
104
return {
71
105
username,
72
- password,
73
- };
106
+ password
107
+ }
74
108
};
75
109
76
110
document .addEventListener (' DOMContentLoaded' , () => {
77
- submitButtonPromise ( ' click ' , ' login' )
78
- . then (() => {
79
- const credentials = readCredentials ();
80
- return login (credentials)
81
- })
82
- . then (( token ) => {
83
- console . log (token);
84
- })
85
- . catch (( err ) => console . log (err) );
111
+ const submitButton = eventSubscription ( ' login' );
112
+ submitButton ( ' click ' ). subscribe (() => {
113
+ const credentials = readCredentials ();
114
+ login (credentials)
115
+ . then (({data}) => {
116
+ console . log (data);
117
+ })
118
+ . catch ( err => console . log (err));
119
+ } );
86
120
});
87
121
```
122
+
123
+ * Modify __ package.json__ to start our app
124
+
125
+ ``` diff
126
+ {
127
+ "name": "temp_auth_review",
128
+ "version": "1.0.0",
129
+ "description": "",
130
+ "main": "index.js",
131
+ "scripts": {
132
+ + "start": "parcel index.html",
133
+ "test": "echo \"Error: no test specified\" && exit 1"
134
+ },
135
+ "keywords": [],
136
+ "author": "",
137
+ "license": "ISC",
138
+ "dependencies": {
139
+ "axios": "^0.19.0"
140
+ },
141
+ "devDependencies": {
142
+ "parcel": "^1.12.3"
143
+ }
144
+ }
145
+
146
+ ```
147
+
88
148
* With our _ auth_ server up and running we can check that this is already working.
89
149
90
- * Ok, so we're retrieving our token we wan to inject it so lets define _ src/API/interceptors.js_
150
+ * Ok, so we're retrieving our token we want to inject it so lets define _ src/API/interceptors.js_
91
151
92
152
``` javascript
93
153
import axios from ' axios' ;
@@ -104,7 +164,7 @@ export const setUpRequest = (token) => {
104
164
* Change _ src/app.js_ to use the token;
105
165
106
166
``` diff
107
- import { submitButtonPromise } from './asyncApi ';
167
+ import { eventSubscription } from './eventEmitter ';
108
168
import login from './API/loginAPI';
109
169
+ import { setUpRequest } from './API/interceptors';
110
170
@@ -113,22 +173,22 @@ const readCredentials = () => {
113
173
const password = document.getElementById('password').value;
114
174
return {
115
175
username,
116
- password,
117
- };
176
+ password
177
+ }
118
178
};
119
179
120
180
document.addEventListener('DOMContentLoaded', () => {
121
- submitButtonPromise('click', ' login')
122
- .then (() => {
123
- const credentials = readCredentials();
124
- return login(credentials)
125
- })
126
- - .then((token ) => {
127
- + .then((result) => {
128
- + const { access_token } = result.data ;
129
- + setUpRequest(access_token);
130
- })
131
- .catch((err) => console.log(err) );
181
+ const submitButton = eventSubscription(' login');
182
+ submitButton('click').subscribe (() => {
183
+ const credentials = readCredentials();
184
+ login(credentials)
185
+ - .then(({data}) => {
186
+ + .then(({data} ) => {
187
+ + const { access_token } = data;
188
+ + setUpRequest(access_token) ;
189
+ + })
190
+ .catch(err => console.log(err));
191
+ } );
132
192
});
133
193
```
134
194
@@ -158,7 +218,7 @@ document.addEventListener('DOMContentLoaded', () => {
158
218
* Lets edit _ src/app.js_ as follows
159
219
160
220
``` javascript
161
- import { submitButtonPromise } from ' ./asyncApi ' ;
221
+ import { eventSubscription } from ' ./eventEmitter ' ;
162
222
import login from ' ./API/loginAPI' ;
163
223
import { setUpRequest } from ' ./API/interceptors' ;
164
224
/* diff*/
@@ -170,29 +230,28 @@ const readCredentials = () => {
170
230
const password = document .getElementById (' password' ).value ;
171
231
return {
172
232
username,
173
- password,
174
- };
233
+ password
234
+ }
175
235
};
176
236
177
237
document .addEventListener (' DOMContentLoaded' , () => {
178
- submitButtonPromise ( ' click ' , ' login' )
179
- . then (() => {
180
- const credentials = readCredentials ();
181
- return login (credentials)
182
- })
183
- . then (( result ) => {
184
- const { access_token } = result . data ;
185
- setUpRequest (access_token);
186
- })
187
- . catch (( err ) => console . log (err) );
238
+ const submitButton = eventSubscription ( ' login' );
239
+ submitButton ( ' click ' ). subscribe (() => {
240
+ const credentials = readCredentials ();
241
+ login (credentials)
242
+ . then (({data}) => {
243
+ const { access_token } = data;
244
+ setUpRequest (access_token) ;
245
+ })
246
+ . catch ( err => console . log (err));
247
+ } );
188
248
/* diff*/
189
- document .getElementById (' cars' )
190
- .addEventListener (' click' , (event ) => {
191
- event .stopPropagation ();
192
- axios .get (' http://localhost:3050/api/cars' )
193
- .then ((result ) => console .log (result))
194
- .catch ((err ) => console .log (err));
195
- });
249
+ const loadCarsButton = eventSubscription (' cars' );
250
+ loadCarsButton (' click' ).subscribe (() => {
251
+ axios .get (' http://localhost:3050/api/cars' )
252
+ .then ((result ) => console .log (result))
253
+ .catch ((err ) => console .log (err));
254
+ });
196
255
/* diff*/
197
256
});
198
257
```
0 commit comments