Context
I work with Angular. I have a service called UserService that handles login, authentication and user data requests.
The get method should check if the user has a valid (not expired) token for authentication before executing the get request. So, if so, make a request; if not, request a token and then execute the request.
Problem
This get method must hide its complex requests. He should return only the promise, since he makes only one request.
So, an example of use:
UserService .get() .then(data => { ... }) .catch(error => { ... })
Wrong decision
Check if the token has expired. If so, return the request to update the token, and there, enter and return the request for receipt. If this is not the case, simply enter and return the request for receipt. As below:
function get() { if (isTokenExpired(token)) return $http .post(url + '/refreshtoken', 'token=' + refreshToken) .then(response => { token = response.data.token return $http.get(url + '?token=' + token) }) .catch(response => { ... }) else return $http.get(url + '?token=' + token) }
But this returns a promise that I will have to handle this:
UserService .get() .then(request => { request // THAT IS NOT GOOD .then(data => { ... }) .catch(error => { ... }) }) .catch(error => { ... })
Something like a usage example!
The right decision
How to make this get method for a service that processes this authentication and hides everything from the controller that it will use, allowing it as in the use case?
javascript angularjs asynchronous
Mateus pires
source share