How to use Firestore on a Spring Boot application

34 Views Asked by At

I'm developing an application with Spring Boot that will be released on Cloud Run. Cloud Run containers are stateless, so to save user experience session information I thought of using Firestore. I will save an instance of the UserService class on the document and the document id is the user id.

public class UserService {
      private Loginform loginForm;
      private SearchForm searchForm;
      private ModifyForm modifyForm;

     //setter and getter method
}

I had thought that in every Controller class (e.g. Home, Search Page, Edit Page etc) to use this technique to return me the information in the user's document:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String clientId = authentication.getName();
        
UserService  userData = getUserService(clientId);

but Authentication is still linked to the session so I would still encounter the container problem. How can I solve it?

Furthermore, in each controller class I have implemented the getUserService(String ClientId) method, perhaps the best solution is to create a Utility Class with the static getUserService method that I can call from each controller class?

public class Utility {

   @Autowired
   private Firestore firestore;

   public UserService getUserService(String clientId) {
       DocumentReference docRef = firestore.collection("users").document(clientId);
       
       ApiFuture<DocumentSnapshot> future = docRef.get();
       
       DocumentSnapshot document = future.get();
       UserService user = document.toObject(UserService.class);
       
       return user;
   }
}
0

There are 0 best solutions below