1
1
const functions = require ( 'firebase-functions' ) ;
2
2
3
- // // Create and Deploy Your First Cloud Functions
4
- // // https://firebase.google.com/docs/functions/write-firebase-functions
5
- //
6
- // exports.helloWorld = functions.https.onRequest((request, response) => {
7
- // response.send("Hello from Firebase!");
8
- // });
3
+ const admin = require ( 'firebase-admin' ) ;
4
+ admin . initializeApp ( functions . config ( ) . firebase ) ;
5
+
6
+
7
+ exports . dialogflowFirebaseFulfillment = functions . https . onRequest ( ( req , res ) => {
8
+
9
+ console . log ( 'Request headers: ' + JSON . stringify ( req . headers ) ) ;
10
+ console . log ( 'Request body: ' + JSON . stringify ( req . body ) ) ;
11
+ // An action is a string used to identify what needs to be done in fulfillment
12
+ let action = req . body . result . action ;
13
+ // Parameters are any entites that Dialogflow has extracted from the request.
14
+ const parameters = req . body . result . parameters ;
15
+
16
+ // Contexts are objects used to track and store conversation state
17
+ const inputContexts = req . body . result . contexts ;
18
+
19
+ // Get the request source slack/facebook/et
20
+ const requestSource = ( req . body . originalRequest ) ? req . body . originalRequest . source : undefined ;
21
+
22
+
23
+ // Firestore database
24
+ const db = admin . firestore ( )
25
+
26
+
27
+ const actionHandlers = {
28
+
29
+ 'phone.update' : ( ) => {
30
+ const userRef = db . collection ( 'users' ) . doc ( 'test-user' ) ;
31
+ const phoneNumber = parameters [ 'phone-number' ] ;
32
+
33
+ userRef . update ( { phone : phoneNumber } ) . then ( ( ) => {
34
+
35
+ const data = formatResponse ( 'No problem. Phone number is updated in Firestore!' )
36
+ res . json ( data )
37
+ } )
38
+
39
+ } ,
40
+ 'default' : ( ) => {
41
+ const data = formatResponse ( 'Hi. I am the default response from the Cloud Function' )
42
+ }
43
+
44
+ }
45
+
46
+ if ( ! actionHandlers [ action ] ) {
47
+ action = 'default' ;
48
+ }
49
+
50
+ // Call the handler with action type
51
+ actionHandlers [ action ] ( ) ;
52
+
53
+ } ) ;
54
+
55
+
56
+ function formatResponse ( text ) {
57
+ return {
58
+ speech : text ,
59
+ displayText : text ,
60
+ data : { } ,
61
+ contextOut : [ ] ,
62
+ source : '' ,
63
+ followupEvent : { }
64
+ }
65
+ }
0 commit comments