Skip to main content

Command Palette

Search for a command to run...

Google Cloud Firestore using Java Microservice

Updated
•1 min read•View as Markdown
M
I am a software developer who likes exploring new things, contribute back to community. My linkedIn profile is https://www.linkedin.com/in/mriduldeka09/

Introduction

Firestore is a scalable NOSQL cloud database built on Google Cloud infrastructure. It can create document and collections in database. In order to connect to firestore by applications, they need service accounts to connect to Google Cloud.

Service Account

Service account is a special account used by app or compute workload engine. It uses email address as unique id. It gives access to resources for which it has permissions. It has keys. To learn more about service account please visit https://cloud.google.com/iam/docs/service-account-overview .

Service account metadata will be in .json file which should be configured as environment variable in project. In IDE, it can be configured under environment variables or in shell script as export command.

GOOGLE_APPLICATION_CREDENTIALS=/Users/mridul/Documents/myProjects/fda/src/main/resources/fda-service-acc.json

Firestore Database client

Below function will give firestore db client or instance which can be used by service.

public Firestore getFirestoreService(){
        //System.out.println("Env "+System.getenv("GOOGLE_APPLICATION_CREDENTIALS"));
        Firestore firestoreService = null;
        try{
            FirestoreOptions firestoreOptions =
                    FirestoreOptions.getDefaultInstance().toBuilder()
                            .setProjectId(projectId)
                            .setCredentials(GoogleCredentials.getApplicationDefault())
                            .build();
            firestoreService = firestoreOptions.getService();
        }catch(Exception ex){

        }
        return firestoreService;
    }
}
public String createOrder(Order order){
        try {
            FirestoreConfig config = new FirestoreConfig();
            Firestore db = config.getFirestoreService();
            OrderMapper orderMapper = new OrderMapper();
            OrderDto orderDto = orderMapper.convertToDto(order);
            DocumentReference docRef = db.collection("orders").document(UUID.randomUUID().toString());
            ApiFuture<WriteResult> result = docRef.set(orderDto);
            return "SUCCESS";
        }catch(Exception ex){
            ex.printStackTrace();
            return "FAILURE";
        }
    }

More from this blog

Software developemnt and Security

6 posts