Google Cloud Function accessing external database

Viewed 1105

I want to access an external database (mongodb) from Google Cloud Function or Firebase Cloud Function. I don't want to create the database connection every time I do it. Is there an option to store the database connection in a global variable and use it in every call.

1 Answers

You can actually do that in a Cloud Function, but you will not be able to control when the connection to your database is created anew and when is reused. If you create the connection object in the global scope, outside the function that is being executed, that piece of code will only be executed whenever a cold start happens. But you will not be able to know when a cold start is happening, so reusing the same connection is not under your absolute control. Check the documentation about the scope of a Cloud Function.

Also, there are other ways to do what you want and keep it under your control. For instance, you can have an Google App Engine application hosting your database connection, and then have a Google Cloud Function send the request to the GAE application.

This way, your GCF will not deal with opening and closing the connection. The service will do it, and the connection will remain open as long as the service keeps running.

Related