Recently, I've been struggling with implementing a logic in my code.
I have a specific requirement:
Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond with a 401 JWT Token Expired error. In such a scenario, I want to trigger another request to refresh the JWT token and then reattempt the original request if successful. If unsuccessful, I need to redirect to the login page.
The current issues I'm facing with this implementation are:
1) The refreshToken() function is located inside ApiService, but I believe it should be in AuthService as it is related to authentication. However, moving the method to AuthService would require me to inject AuthService into ApiService, leading to a circular dependency issue. Additionally, I am unsure how to pass arguments in the constructor for AuthService to make the .super(args) call.
2) My code is currently not functioning properly due to this part:
this.refreshToken().toPromise().then(() => {
if (request.data) {
console.log('POST');
return this[request.method](request.endpoint, request.data);
} else {
console.log('GET');
return this[request.method](request.endpoint);
}
});
Since refreshToken is asynchronous, I cannot directly call the original method. How can I address this issue?
Here is an example of my code:
DataService
// Code for DataService
// ...
ApiService
// Code for ApiService
// ...
TendersService
// Code for TendersService
// ...
AuthService
// Code for AuthService
// ...