☁ Cloud Firestore with Actions on Google - Part 1/2
Tags: actionsongoogle, dialogflow, firestore, database
Published: 2020-03-20 06:29:41

Hello AoG Devs!!

This is part one of Cloud Firestore with Actions on Google Series, in this part I will show you how to store data in Cloud Firestore. 

Prerequisite:
1. Knowledge of Dialogflow ([Check terminologies post](https://dev.to/smitjethwa/dialogflow-terminologies-3i46))
2. Javascript

I'll recommend you to go through Cloud Firestore terminologies first([Check docs](https://firebase.google.com/docs/firestore))

__Cloud Firestore__ is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in documents, which are organized into collections.
E.g. 
![Snapshot of Firestore](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2FCapture.PNG?alt=media&token=78530556-742b-4439-9bc7-8c2e519e1203 "Snapshot of Firestore")
==========
In short, 
1. Field - A data (e.g. 'capital':'New Delhi')
2. Document - Set of Fields. 
(e.g. India:{'capital':'New Delhi','currency':'Rupee'})
3. Collection - Set of Similar kinds of Documents (e.g. Country includes India, USA, Sri Lanka etc.)

I hope, you are now familiar with the terms, so let's get started with the implementation!
### Step 1 
#### Create the intent which will take the User's name and User's Email Address.
![SetDetails Intent](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F2.PNG?alt=media&token=5d2d45f1-d70d-4125-af60-ed1adbfe528b "SetDetails Intent")

### Step 2
#### Set Parameter name and tick _required_ field for both the parameters i.e. _**name**_ and _**email**_
![Step: 2](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F3.PNG?alt=media&token=ada73975-5174-4852-84d6-987ee3b0eff4 "Step 2")

### Step 3
#### Switch to _[Firebase Console](https://console.firebase.google.com/u/0/)_ and click on _Database_, select _Cloud Firestore._ 
3.1 Give Collection name as _userDetails_
3.2 Create one Document.
It should look like the below image.
![userDetails](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F4.PNG?alt=media&token=8a6e054b-c9e2-42b4-a504-2cabfd46eeed "Snapshot of userDetails Collection")
Final Document with one collection and field.
![userDetails](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F5.PNG?alt=media&token=a25ea641-ae9c-4467-a84b-cb9f025fef4d "Snapshot of userDetails Collection")

### Step 4
#### Let's code! (_Javascript_)
Click on _Fulfillment_, Enable _Inline Editor_
* import required modules.
``` javascript
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
```

* Initialize Firestore
``` javascript
admin.initializeApp();
const db = admin.firestore();
```
* enables lib debugging statements
``` javascript
process.env.DEBUG = 'dialogflow:debug'; 
```

* Set the DialogflowApp object to handle the HTTPS POST request
``` javascript
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });
```

* Create a function to store data. 
_agent.parameters.name_ and _agent.parameters.email_ returns the name and email address of the user respectively. 
``` javascript
function getNameHandler(agent) {
    let name = agent.parameters.name;
    let email = agent.parameters.email;
    db.collection("userDetails").add({      // this method will insert the data in firestore
      name: name,       
      email: email
    });
```

* Map the intent name and functions
``` javascript
 let intentMap = new Map();
  intentMap.set('setDetails', getNameHandler);
  agent.handleRequest(intentMap);
```

#### Complete Code:
``` Javascript
'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function getNameHandler(agent) {
    let name = agent.parameters.name;
    let email = agent.parameters.email;
    db.collection("userDetails").add({ 
      name: name,
      email: email
    });
    agent.add('Data added successfully!!');
  }

  let intentMap = new Map();
  intentMap.set('setDetails', getNameHandler);
  agent.handleRequest(intentMap);
});
```
Deploy the function

### Step 5
#### Open Simulator
Enter the Test Name and Email Address.
![Test Image](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F6.PNG?alt=media&token=dcf5b3dd-51a4-4852-a648-1da21b478c02 "Input sample image")

After the message _Data added successfully!!_ Check Firestore. There will be one entry of the given input.
![Test Image](https://firebasestorage.googleapis.com/v0/b/megahack-146b8.appspot.com/o/firestore-part-1%2F7.PNG?alt=media&token=b0df743a-5820-44e6-bc01-d371b718673a "Input sample image")

I hope, this post will help to understand firestore with Actions on Google. This is part of a series of posts. In the next post, I'll explain how to read the data from Cloud Firestore. Till then Happy Coding!! 

Read Part 2 [here](https://dev.to/smitjethwa/cloud-firestore-with-actions-on-google-part-2-2-52am)

Share your experience, and doubts in the comments or let's get connected with me on [Twitter](https://twitter.com/jethwa_smit). 



<!-- 
start creating the collection.
In this example, I've created a collection named Details, where I'll store the User's Name, User's Email Address.
1. Create the Collection name _details_. (Note the collection name)
2. 
-->
<!--

#### Field: 
Fields are the data which is going to be stored in firestore. 
The field for an Indian document can be 
> _**capital**_:_New Delhi_
> _**currency**_:_Rupee_  

A field for the USA document can be 
> _**capital**_:_Washington D.C._
> _**currency**_:_Dollar_
> _**states**_:_50_

The number of fields per document may vary. 


####Document: 
In Cloud Firestore, the unit of storage is the document. A document is a record that contains fields. India, the USA, Australia etc are examples of Documents.
Here,
India:{'capital':'New Delhi','currency':'Rupee'}
USA : {'capital':'Washington D.C.','currency','states':50}

####Collection:
The collection is a set of Documents. For example country, ocean, etc.
Country:
{
India:{'capital':'New Delhi','currency':'Rupee'},
USA : {'capital':'Washington D.C.','currency','states':50}
},
Ocean:
{
.
.
.
}
 
-->