Write Cloud Functions on Cloud Firestore and deploy – Introduction

May 16, 2019
Contents
> What is Cloud Firestore >What are Cloud functions >Writing and Deploying Cloud Functions to write data to Cloud Firestore Collection

What is Cloud Firestore

It’s a NoSQL document database that lets you store data for your Mobile Application, web Application, APIs…
It is Cloud-based, highly scalable and flexible.

To see your Firestore database dashboard visit the below URL

https://console.firebase.google.com/project/YOURPROJECTNAME/overview

Firestore has the following Datatypes

string
number
boolean
map
array
null
timestamp
geopoint
reference

Firestore is a Document database.We can save data as collections -> documents  ->  subcollections in a nested structure.

Here we can see that the created date is a timestamp ,reciever_data is a map and reciever_id is a string data.

What are Cloud functions

Cloud Functions help to achieve serverless execution by providing access to Firebase and Cloud events .Operations can be done in response to these events.
For example, you can do CRUD operations on the Firestore / Realtime database using Cloud Functions. You can deploy the Cloud function and hit them to perform these CRUD operations. The event handler for an HTTP request to the Cloud Functions listens for the onRequest event

Writing and Deploying Cloud Functions to add data to Cloud Firestore Collection

step 1 We can install Firebase CLI via npm using the following command provided you have npm available in your system.

 

step 2 Run the following command to log in to Firebase using the Firebase CLI

This will give a URL which can be opened in the browser and used to login using your google Id and Password

step 3 Navigate to your desired firebase functions folder and run the following command to initialize your firebase functions project

 

This will create files including index.js file and package.json file.index.js file will have your firebase functions and package.json file will have dependencies

step 4 Create Cloud functions

To create a Cloud Function which adds to your Cloud Firestore you need to install and import the following modules

in index.js file

 

Now we write a function to add a document to a collection messages

 

step 5 Deploy functions

Run the following command to deploy the function

 

This will give a URL to the function like the following

https://us-central1-yourprojectname.cloudfunctions.net/AddMessages

Hitting the URL with a post request from Postman with the desired data will create the collection

We will see more about securing your request URL later in the next part of this tutorial

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *