Onk_r
Onk_r

Reputation: 846

Node.js cloud function "firestore set() inside get() if not exists" is not working correctly?

Here is I'm trying to achieve

if user is exist in firestore 
      show the data 
else
      add it to firestore

And following is my code

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

var db = admin.firestore();
const settings = {timestampsInSnapshots: true};
db.settings(settings);

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

    function save(agent) {
        const usersRef = db.collection('users').doc('someid');
        usersRef.get().then(function(doc) {
            if(doc.exists) {
                let existingUser = doc.data();
                console.log("Document is already exists " + existingUser.userName);
                agent.add('Hello ');
            } else {
                console.log("Document creation is started");
                usersRef.set({
                    userName : 'somename'
                });
                agent.add('Welcome ');
            }
        }).catch(function(error) {
            console.error("Error writing document: ", error);
            agent.add('Failed to login!');
        });
    }
    let intentMap = new Map();
    intentMap.set('dialogflow-intent-name',save);
    agent.handleRequest(intentMap);
});

But the execution of above code it starts the cloud function and terminated first and my chatbot doesn't get any response but after execution log is like

Upvotes: 1

Views: 519

Answers (1)

Ricardo Smania
Ricardo Smania

Reputation: 3139

DocumentReference.set returns a promise, and you are not waiting for it to finish. So it should work if you change your code from:

usersRef.set({
    userName : 'somename'
});
... rest of the code

to

usersRef.set({
    userName : 'somename'
}).then(result => {
    ... rest of the code
})

Upvotes: 1

Related Questions