ROSARIO FERNANDES: Great, I just finished writing all the client
code for my Android app.
And I'm ready to write my server-side logic.
Let's see, Cloud Functions, TypeScript, JavaScript,
and Python?
Where's my Kotlin?
ALEXANDER NOHE: Maybe I can help.
[MUSIC PLAYING]
ROSARIO FERNANDES: Do you love using Firebase
but want to feel more comfortable using
your own preferred coding language to develop
your server-side logic?
And what about reacting to events
that occur in Firestore or at the server-side events?
ALEXANDER NOHE: That is where Cloud Events can help.
We recently introduced second-generation Cloud
Functions in Firebase.
So as your data changes in Firestore,
you can deploy your own function to react to those changes.
Second-generation Cloud Functions
are built off of the Cloud Event spec
and implemented in Google Cloud under our implementation called
Eventarc.
These are events that can be emitted in Google Cloud.
And you can listen and react to them as necessary.
ROSARIO FERNANDES: Out of the box,
Cloud Functions for Firebase supports
JavaScript, TypeScript, and more recently, Python.
But wouldn't you prefer to write your code in Kotlin?
Best language ever!
In this video, we're going to cover step-by-step
how to write, deploy, and test a Google Cloud
function in Kotlin that is triggered
by an event in Cloud Firestore.
ALEXANDER NOHE: To do so, we are going to build a yelling robot
together.
As data is changed in our Firestore database,
we are going to convert all the characters to uppercase
to simulate the Firestore instance yelling.
This is a simple use case that will
allow us to see changes immediately and prove out
that our functions are working correctly.
ROSARIO FERNANDES: Although we are writing in Kotlin today,
you could realistically write in any language that is supported
by the Firebase Admin SDK.
The Admin SDK allows you to access Firebase
from your backend code without the need
for an authorized user.
This gives the server-side code higher privilege
to underlying services and is authenticated
with a service account.
There may be third-party libraries that
exist outside of our admin SDKs and support
writing to Firestore, but that is
beyond the scope of this video.
ALEXANDER NOHE: If you want to code along with us,
the source code is available in the repository listed
in the description below.
Let's start by setting up our Firebase project
in the Console.
First go to console.firebase.google.com.
After signing in with a Google account,
click Start a New Project and give it a name.
The next screen will give you the option
to enable Google Analytics for your Firebase project.
This is optional.
But it's recommended because it enables useful features
like the ones you see listed here.
If you do decide to enable Analytics,
you need to select a Google Analytics account
and finally click on the Create Project button.
Once the project is configured, you
can open the Firestore dashboard.
Since you're going to be reacting
to changes that occur in the database,
let's create a Firestore database.
Here, you can select to start in production mode.
Don't forget to create strong security rules
to make sure the data in your database
can only be created, read, updated, and deleted
by people who have the right to perform these actions.
To keep your data safe and secure,
you should write security rules.
This is outside the scope of this video.
But to learn more, check out the video linked in the description
below.
Lastly, choose a location for your database
and click Finish to create it.
The next step is to set up Cloud Functions.
To do so, you'll need to update your billing plan from Spark
to Blaze.
Cloud Functions require you to add your billing information.
But you will only be charged if you exceed
the quota for this product.
If you want to get an estimate for your monthly costs
on the Blaze plan, you can simulate this using the Blaze
plan calculator.
The link is available in the description below.
Upgrading your pricing plan is easy.
Click on the Upgrade button at the bottom-left corner
of the Firebase Console and follow the steps on screen
ROSARIO FERNANDES: Now you need to set up
your local environment.
The first thing to do is to install the Google Cloud
CLI, also known as gcloud.
The link to the documentation with the step-by-step
instructions to install gcloud can be found in the description
below.
Once you have that installed, you
need to authenticate with the same account you
used to sign in to Firebase.
After signing in, you need to select
the Firebase project you just created
by providing the project ID.
This information is needed in order
to deploy the Cloud Function later.
If you want to double-check the setup
to confirm it's the right project,
you can run gcloud, config, get project.
ALEXANDER NOHE: Before writing the function,
there are two more things you need to do--
grant some permissions in the Google Cloud Console
and enable the Cloud Run API.
First, navigate to the Cloud Run API
and enable it so you can utilize Cloud Run, which
powers our functions.
Then navigate to the Identity and Access Management
dashboard.
From here, click on the Edit button
and add to the default compute account a few permissions.
The first permission is the Cloud Run invoker.
And the second one is the Eventarc event receiver.
ROSARIO FERNANDES: OK, now you're
ready to write the Cloud Function.
Start by creating a new Maven project
and add a few dependencies to it for Kotlin
and these other dependencies for Cloud Function support.
When a Cloud event comes in, it will
contain some information that the actual event that
meets the specification.
These are things like the ID of the event, the source, data
content type, and format.
We have placed one event on the screen for us
to jointly take a look at.
Looks confusing, right?
If we look closer at the event, we
can see its type is protobuf.
Protobuf is an efficient write format
that allows us to decode it using another library that we
installed.
So in our code, we will call DocumentEventData.parseFrom
and supply our binary protobuf.
This will then give us the option
to work with the binary data in a usable format.
From here, we have access to the previous and current values
of the document field and much more.
You'll find the link to the protobuf we are using
and to the library with compiled Cloud
events in the description.
Once we have that, all we do is search for the desired field
we want to change and then check if it's in the desired state.
In this example, we're checking if the content
is all in uppercase.
If it's not, we convert it to the desired state
and write it back to the document in Firestore
using the Admin SDK.
We've written the function.
Let's deploy it.
Navigate to this projects folder and get
ready to type a really long command.
The command starts with calling the CLI
and determining what part of Cloud you want to work with
and what you want that part of Cloud to do.
In our case, it's deploy.
Then give the function a unique name
for subsequent deployments.
You can reuse this name to update the function.
Next, specify that this is a second-generation Cloud
Function by adding gen2 to the command.
This is needed so you can receive Eventarc triggers.
Then you need to determine the entry point
in the code and the runtime that you have
developed this code against.
In our case, we developed this against Java 17.
And we'll be using the Firebase uppercase text function
in the functions package.
Next in this command, you need to specify the trigger
information, such as where the Firebase trigger is originating
from, what type of Firestore events we are interested in,
and what is the path pattern we want to observe
and the location of the database.
In this case, we're interested in the written event,
specifically for documents stored in the yell collection.
The last variables that you need to set
are the project that is running this command and the region
where this function will run, as well as the memory size
allocation for the function.
After adding all this info, you can run the command.
You'll probably have to hit Yes a few times
to allow this function to enable a series of APIs
for this to work.
For example, Cloud Build, Eventarc, and Cloud Functions.
If the deployment was successful,
you should be able to see the Cloud Function in the dashboard
in the Firebase Console.
Oh, there it is.
Now the fun part.
Let's test this function.
Remember, we specified that we want this Cloud
Function to run whenever a document is
updated in Cloud Firestore.
An easy way to test this is to go to the Firebase Console
and use the Firestore viewer to create a new document.
So here, I create a new collection
with the same name I used when I registered the Cloud
Function in the previous step.
In this collection, I'll create a new document
with a field of type string, make sure
that the field name is the same used in Cloud Function,
and enter a value for this field.
Don't forget that the value should be in lowercase so you
can see the function in action.
In the background, my Cloud Function
now converts the value to uppercase
and writes it back to the document.
This just takes a short moment.
And there it is.
The document is updated.
And the value of the field is now all uppercase.
And if you want to look at the logs,
you can do so in the Google Cloud Console.
An easy way to find them is through the Firebase Console
by navigating to the Cloud Functions dashboard,
clicking on the three-dot menu, then on the View Logs option.
It will take you straight to the logs page in the Cloud Console,
where you can search for data using a variety of filters.
ALEXANDER NOHE: This is a reminder that deploying Cloud
Functions using the gcloud CLI will not provide the same
out-of-the-box features that you may get with deploying
the Firebase-supported Cloud Functions.
For instance, in our Kotlin Cloud Function,
we need to parse the protocol buffer,
lint, and check our own code for deployment,
and had to manually set up Eventarc
to communicate with the appropriate function.
Whereas when using Firebase to deploy,
the Firebase CLI handles these things on your behalf.
ROSARIO FERNANDES: And that's all we
wanted to share with you today.
Now you're able to use the same language
that you use in Android apps in your Cloud Functions.
And there's much more you can do with Cloud
Functions in many other programming languages.
Check out the Google Cloud and Firebase documentation
to learn more.
ALEXANDER NOHE: If you liked this codealong,
give this video like and subscribe to the Firebase
YouTube channel.
And feel free to send it to someone
who you may think like it, too.
I'm Alexander Nohe.
ROSARIO FERNANDES: And I'm Rosario,
reminding you that Kotlin isn't just for client apps.
[MUSIC PLAYING]