How to disable too many logs of actions-on-google – api.ai

this code is giving me un expected logs, my question is how can i remove these logs then it will be easy for me to point out my own developer log

here is my code:

process.env.DEBUG = 'actions-on-google:*';
import * as admin from 'firebase-admin';
const Assistant = require('actions-on-google').ApiAiAssistant;
import * as functions from 'firebase-functions';
import data from './../../db/index';
import { Request, Response } from "express";
import * as functionRequest from 'request';

// API.AI Action names
const SUBMIT_REPORT = 'submitReport';
const NEXT_QUESTION = 'next_question';

export const webhook = functions.https.onRequest(async (request: Request, response: Response) => {
    const assistant = new Assistant({ request: request, response: response });

    let actionMap = new Map();

    actionMap.set(SUBMIT_REPORT, submitReport);
    actionMap.set(NEXT_QUESTION, next_question);

    assistant.handleRequest(actionMap);

    function submitReport(assistant: any) {

        console.info("user ask for submit report, request body: ", request.body);

        let dataRef = request.body.originalRequest.data.user;
        let userData = {
            groupId: dataRef.groupId,
            subgroupId: dataRef.subgroupId,
            userId: dataRef.userId
        }
        //console.log("userdata: ", userData)
        let botRef = data.db.ref('subgroup-bot-chat-mode/' + userData.groupId + '/' + userData.subgroupId + '/' + userData.userId)
        botRef
            .once('value', function (snapshot) {
                let data = snapshot.val()
                //console.log("here is recieved data: ", data)
                if (data == null) {
                    let entry = {
                        'userAgreed': true,
                        'askedForReport': true,
                        'timestamp': admin.database.ServerValue.TIMESTAMP,
                        'reportIndex': 0,

                    }
                    botRef
                        .set(entry, function (error) {
                            if (!error) {
                                //console.log("Data save successfully at subgroup-bot-chat-mode/")

                                // start asking questions
                                const fullfillment = {
                                    "speech": "qedfqwedf",
                                    "followupEvent": {
                                        "name": "ESOX_WRITE_STANDUP_REPORT_NOW"
                                    },
                                    "contextOut": [
                                        {
                                            "name": "quiz",
                                            "lifespan": 5,
                                            "parameters": {
                                                "index": "0"
                                            }
                                        },
                                        {
                                            "name": "sendReportNow-followup",
                                            "lifespan": 5,
                                        },
                                    ]
                                }
                                response.send(fullfillment);
                                return;
                            }
                        }).catch((e) => {
                            console.error("1. an error occured when getting data from db");
                            response.send({
                                speech: "error on db"
                            })
                            return;
                        })

                } else {
                    response.send({
                        speech: "already"
                    })
                    return;
                }
            }).catch((e) => {
                console.error("2. an error occured when getting data from db");
                response.send({
                    speech: "error on db"
                })
                return;

            })

    }
    function next_question(assistant: any) {

        let dataRef = request.body.originalRequest.data.user;
        let userData = {
            groupId: dataRef.groupId,
            subgroupId: dataRef.subgroupId,
            userId: dataRef.userId
        }

        let questionIndex = request.body.result.contexts[0].parameters.index;
        console.log("index: ", questionIndex);

        // if question index == 0 it means it is first time, we will send first question to user
        // if question index > 0 it means it means user is answered th index
        if (questionIndex == 0) {
            console.log("going to send first question");
        } else if (questionIndex > 0) {
            //todo: process answer here
            console.log("answer: ", request.body.result.parameters.answer);
            let answer = request.body.result.parameters.answer;


            // data.db.ref('subgroup-progress-reports/' + userData.groupId + '/' + userData.subgroupId + '/' + userData.userId + '/' + reportId + '/answers/' + reportIndex)
            //     .set(answer)


        }


        // start asking questions
        functionRequest({
            url: 'https://us-central1-luminous-torch-4640.cloudfunctions.net/getReportQuestions',
            method: 'POST',
            json: {
                'groupId': userData.groupId,
                'subgroupId': userData.subgroupId,
                'userId': userData.userId
            }
        }, function (error, res, body) {
            if (!error && response.statusCode == 200) {
                //console.log("hello: ", res.body)
                switch (res.body.status) {

                    case 'EOF':
                        response.send({
                            "speech": "EOF",
                            "contextOut": [
                                {
                                    "name": "quiz",
                                    "lifespan": 0
                                },
                                {
                                    "name": "sendReportNow-followup",
                                    "lifespan": 0,
                                }
                            ]
                        })
                        break;

                    case 'OK':
                        //sending question back
                        let botRef = data.db.ref('subgroup-bot-chat-mode/' + userData.groupId + '/' + userData.subgroupId + '/' + userData.userId)
                            .update({
                                reportIndex: res.body.reportIndex,
                                reportId: res.body.reportId
                            })

                        response.send({
                            "speech": res.body.question,
                            "contextOut": [
                                {
                                    "name": "quiz",
                                    "lifespan": 5,
                                    "parameters": {
                                        "index": res.body.reportIndex,
                                        "reportId": res.body.reportId
                                    }
                                },
                                {
                                    "name": "sendReportNow-followup",
                                    "lifespan": 5,
                                }
                            ]
                        })

                        break;
                    case 'ALREADY_ASKED_FOR_TODAY':
                        response.send({
                            "speech": "you are already submited the report for today",
                            "contextOut": [
                                {
                                    "name": "quiz",
                                    "lifespan": 0
                                },
                                {
                                    "name": "sendReportNow-followup",
                                    "lifespan": 0,
                                }
                            ]
                        })
                        break;
                    default:
                        console.error("Unknown case");
                        //http request failed
                        response.send({
                            "speech": "Something went wront on question server",
                            "contextOut": [
                                {
                                    "name": "quiz",
                                    "lifespan": 0
                                },
                                {
                                    "name": "sendReportNow-followup",
                                    "lifespan": 0,
                                }
                            ]
                        })
                        return;
                }
            } else {
                //http request failed
                response.send({
                    "speech": "Something went wront on question server",
                    "contextOut": [
                        {
                            "name": "quiz",
                            "lifespan": 0
                        },
                        {
                            "name": "sendReportNow-followup",
                            "lifespan": 0,
                        }
                    ]
                })
            }
        })
    }

})//end of webhook http trigger

logs of firebase functions are here:

2:10:34.707 PM info webhook Sat, 05 Aug 2017 09:10:34 GMT
actions-on-google:debug map of intents
2:10:34.707 PM info webhook Sat, 05 Aug 2017 09:10:34 GMT
actions-on-google:debug name=next_question 2:10:34.707 PM info
webhook Sat, 05 Aug 2017 09:10:34 GMT actions-on-google:debug key is
id 2:10:34.706 PM info webhook Sat, 05 Aug 2017 09:10:34 GMT
actions-on-google:debug name=submitReport 2:10:34.706 PM info webhook
Sat, 05 Aug 2017 09:10:34 GMT actions-on-google:debug key is id
2:10:34.706 PM info webhook Sat, 05 Aug 2017 09:10:34 GMT
actions-on-google:debug invokeIntentHandler_: handler=[object Map],
intent=next_question


Source: stackoverflow-javascript

Write json file to Firebase with Node.js?

I have a third party API that I need to call every 5 seconds. I get JSON as response, and I’d like to write the JSON content to a Firebase node using Node.js. Based on Firebase examples I could import data with this code:

var usersRef = ref.child("users");
usersRef.set({
  alanisawesome: {
    date_of_birth: "June 23, 1912",
    full_name: "Alan Turing"
  },
  gracehop: {
    date_of_birth: "December 9, 1906",
    full_name: "Grace Hopper"
  }
});

Curl examples worked too. But what I really wanted to do is to import a third party API response directly to my Firebase database using the API endpoint. How can i do it with Node.js?


Source: stackoverflow-javascript

React-native and Firebase: Wait for Firebase data

I am currently implementing an application which relies on Firebase data before it can continue. However, I often (unless I deliberately wait) get the result Cannot read property [property] of null. I very much suspect that this is because the firebase request could not be made before I call this object.

Now I am looking for methods to implement a rendez-vous, or a barrier, really anything that implements a checkpoint where all firebase data are received, before it continues. Is there anything in Javascript which helps me to do so, or any library, or any react-native library that helps me to achieve this?

My code looks as follows: (Fb is the firebase interface)

@action
  bookInterestedBike() {
    this.bookedBikeNo = this.interestBikeNo;
    this.downloadBikeObj();
    this.updateBikeDataStartRide();
    this.updateUserDataStartRide();
    //
    //This is where the firebase checkpoint / barrier should happen, and no progress should be made unless this data was fetched!
    //
    this.startTimer();
  }

@action
  downloadBikeObj() {
    Fb.staticBikes.child(String(this.bookedBikeNo)).once('value', (bikeObj) => {
      this.bikeObj = bikeObj.val();
      console.log("Save object is: ");
      console.log(this.bikeObj);
    });
  }

  updateBikeDataStartRide() {
    var updateVals = {}
    updateVals[this.interestBikeNo] = {
      bike_no: this.interestBikeNo,
      current_user: "self",
      positionLat: this.usrLat,
      positionLng: this.usrLng
    };
    Fb.bikes.update(updateVals);
    return false;
  };

  updateUserDataStartRide() {
    var updateVals = {}
    updateVals[this.uuid] = {
      bike_no: this.bookedBikeNo,
      uuid: this.uuid //TODO: remove this in deployment
    };
    Fb.users.update(updateVals);
    return false;
  };


Source: stackoverflow-javascript

Making a Handlebars Template from a Firebase JSON

I have a handlebars template that worked fine using the old fashioned XMLHttpRequest to get the JSON array from https://learnwebcode.github.io/json-example/pets-data.json. Below is the working code for that. But my JSON from Firebase looks different, like this: http://pastebin.com/JaYVVzwN. Every entry of mine also has a key, while the LearnWebCode JSON is just an array. Mine is also missing the parent key (‘Projects’), which further complicates the transition. I’m thinking it might be due to the line with const dbRefObject = firebase.database().ref().child('Projects'); (see the very bottom where I post my attempted javascript)

handlebars-project.js: Old-fashioned XMLHttpRequest

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/pets-data.json');
ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
        var data = JSON.parse(ourRequest.responseText);
        createHTML(data);
    } else {
        console.log("We connected to the server, but it returns an error.");
    }
};

ourRequest.onerror = function () {
    console.log("Connection error");
};

ourRequest.send();

function createHTML (petsData) {
    var rawTemplate = document.getElementById("petsTemplate").innerHTML;
    var compiledTemplate = Handlebars.compile(rawTemplate);
    var ourGeneratedHTML = compiledTemplate(petsData);

    var petsContainer = document.getElementById("pets-container");
    petsContainer.innerHTML = ourGeneratedHTML;
}

And here’s the working HTML/Handlebars code:

card-handlebars.php: Basic template I want to use (it makes a little card. I want a lot of these, one for every item under the Projects key from the Firebase JSON)

Now I want to switch that first handlebars-project.js code over to using firebase instead.

To be clear, I want my page to be populated with a bunch of these cards (I’m using Semantic UI) for every item under the Projects key (Project-1, Project-2, Project-3, etc.) from a single Firebase fetch. It’s already being stringified to JSON. I want the looping to stay in handlebars (HTML), not in the javascript. And this isn’t using Node.js.

Here’s a look at my actual Firebase table:

Firebase
Here’s my attempt at the javascript:

handlebars-firebase-project.js: Not working. This is where the crux of the whole issue is. It should be a simple fix but I’m no JS expert.

(function() {

  // https://www.gstatic.com/firebasejs/3.7.1/firebase.js

  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyAC1MEF59loMVRA7zyaMhn6uHrp4i2OPNw",
    authDomain: "website-171c8.firebaseapp.com",
    databaseURL: "https://website-171c8.firebaseio.com",
    storageBucket: "website-171c8.appspot.com",
    messagingSenderId: "642759134369"
  };
  firebase.initializeApp(config);

  //Create references
  const dbRefObject = firebase.database().ref().child('Projects');

  //Sync object changes (HTML)
  dbRefObject.on('value', snap => {

    var rawTemplate = document.getElementById("petsTemplate").innerHTML;
    var compiledTemplate = Handlebars.compile(rawTemplate);
    var ourGeneratedHTML = compiledTemplate(JSON.stringify(snap.val(), null, 3));

    var petsContainer = document.getElementById("pets-container");
    petsContainer.innerHTML = ourGeneratedHTML;

  });

}());


Source: stackoverflow-javascript

firebase async – cant access object data

$('#btn_searchUser').click(function(){
  var emailSearch = $('#txt_searchEmail').val();
  var rootRef = firebase.database().ref('users/');

  rootRef.orderByChild('email').equalTo(emailSearch).once('value').then(function(snapshot){

   displayUserDetails(snapshot);
 }, function(error){
   console.log(error);
 });
});
function displayUserDetails(snapshot) {
var data = snapshot.val();
console.log(data);
}

logging the data logs the object as expected… but data.name or any other method ive tried logs undefined!

Very new to JS so any help is appreciated. Thanks


Source: stackoverflow-javascript