I have a Service which makes various API calls using a Client class. The APIs require a token which can expire. This token is saved in the db so I only fetch for a new token when it expires. I’m looking for a clean way to write this code. Currently, the pseudo code looks something like this:
public class Service {
@Autowired
private Client client;
public void createUser() {
Token token = readTokenFromDb();
if (token.isExpired()) {
token = client.readToken();
save(token);
}
client.createUser(token);
}
public void readUsers() {
Token token = readTokenFromDb();
if (token.isExpired()) {
token = client.readToken();
save(token);
}
client.readUsers(token);
}
public void updateUsers() {
// similar code
}
// many other similar methods
}
What's the best way to avoid the if block to refresh the token for every method? In other words, have one common place to do it.
If it matters, this is a Spring project, and the Client is using an @Autowired RestTemplate inside for calling the APIs.
Aucun commentaire:
Enregistrer un commentaire