Context
I'm working with Angular. I have a service called UserService, that handles login, authentication and user data requests.
The get method needs to check if the user has a valid (not expired) token for authentication before making the get
request.
So, if it has, make the request, if not, request a token and then make the request.
Problem
This get method needs to hide its complex requests. It has to return only a Promise as it was making only one request.
So, an example of usage:
UserService
.get()
.then(data => { ... })
.catch(error => { ... })
Wrong solution
Check if the token is expired. If it is, return a request to refresh the token, and there, make and return the get request. If it is not, just make and return the get request. 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 it's returning a promise that I will have to handle like this:
UserService
.get()
.then(request => {
request // THAT IS NOT GOOD
.then(data => { ... })
.catch(error => { ... })
})
.catch(error => { ... })
Anything like the usage example!
Correct solution
How to make this get method on service, which handles authentication like that and hides everything from the controller that will use, letting it like in the usage example?