вызов файла json из функции firebase - PullRequest
0 голосов
/ 10 декабря 2018

У меня есть 3 группы (html) внутри каждой группы, по четыре человека, и эти люди одинаковы во всех 3 группах, но просто разные цифры (голоса / кредиты), и у меня есть файл json, где находятся значения для этих людей внутригруппа.Мой HTML-файл без проблем читает мой JSON-файл.

Я использую встроенный редактор Dialogflows для работы с Google Assistant.Я хочу, чтобы точно так же, как мой html (javascript) считывал эти значения из файла json, я хочу также иметь возможность загружать файл person.json.Я редактировал, что много раз не мог дозвониться до person.json url.

Например:

«Привет, Google, скажи мне, что кредиты Алекса»
<здесь это должно читаться из моего файла json, который 73>

Вот коды: person1.html

document.addEventListener("DOMContentLoaded", async function(event) {
    var response = await fetch("person.json");
    var arr = await response.json();
    var personparsed = arr[1];

            var dflt = {
              min: 0,
              max: 100,
           //   donut: true,
              gaugeWidthScale: 1.1,
              counter: true,
              hideInnerShadow: true
            }

            var ee1 = new r({
              id: 'ee1',
              value: personparsed['Jennifer'],
              title: 'Jennifer ',
              defaults: dflt
            });

            var ee2 = new r({
              id: 'ee2',
              value: personparsed['Peter'],
              title: 'Peter',
              defaults: dflt
            });
        	
        	    var ee3 = new r({
              id: 'ee3',
              value: personparsed['Justin'],
              title: 'Justin',
              defaults: dflt
            });
        	
        	    var ee4 = new r({
              id: 'ee4',
              value: personparsed['Alex'],
              title: 'Alex',
              defaults: dflt
            });

          });

встроенные редакторы index.js:

// 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 {Card, Suggestion} = require('dialogflow-fulfillment');
 
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
 
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
 
  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }
 
  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}

  // // Uncomment and edit to make your own intent handler
  // // uncomment `intentMap.set('your intent name here', yourFunctionHandler);`
    // // below to get this function to be run when a Dialogflow intent is matched
  // function yourFunctionHandler(agent) {
  intentMap.set('persons1', someFunction);
function someFunction(agent) {
    agent.add(`Alex credits are 73 `);
}
  // // below to get this function to be run when a Dialogflow intent is matched
  // function yourFunctionHandler(agent) {
  //   agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`);
  //   agent.add(new Card({
  //       title: `Title: this is a card title`,
  //       imageUrl: 'https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png',
  //       text: `This is the body text of a card.  You can even use line\n  breaks and emoji! ?`,
  //       buttonText: 'This is a button',
  //       buttonUrl: 'https://assistant.google.com/'
  //     })
  //   );
  //   agent.add(new Suggestion(`Quick Reply`));
  //   agent.add(new Suggestion(`Suggestion`));
  //   agent.setContext({ name: 'weather', lifespan: 2, parameters: { city: 'Rome' }});
  // }

  // // Uncomment and edit to make your own Google Assistant intent handler
  // // uncomment `intentMap.set('your intent name here', googleAssistantHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function googleAssistantHandler(agent) {
  //   let conv = agent.conv(); // Get Actions on Google library conv instance
  //   conv.ask('Hello from the Actions on Google client library!') // Use Actions on Google library
  //   agent.add(conv); // Add Actions on Google library responses to your agent's response
  // }
  // // See https://github.com/dialogflow/dialogflow-fulfillment-nodejs/tree/master/samples/actions-on-google
  // // for a complete Dialogflow fulfillment library Actions on Google client library v2 integration sample

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

1 Ответ

0 голосов
/ 11 декабря 2018

У вас есть несколько вариантов здесь.Либо вы переключаете свой план на Blaze и делаете сетевой запрос на данные JSON, которые размещены на вашем общедоступном URL, упомянутом ранее.

Или вы также можете просто поместить данные JSON в базу данных реального времени Firebase, так какдоступен как документ JSON по общедоступному URL-адресу, если для правил базы данных установлено общедоступное доступное для чтения .

database.rules.json

{
  "rules": {
    "persons": {
      ".read": true
    }
  }
}

После этого вы можете получить доступ к своим данным JSON в Firebase по этому URL: https://<your-project-id>.firebaseio.com/persons.json

Это должно быть практически то же самое для доступа в вашем веб-приложении.

Для выполнения AoG вы можетепросто используйте Firebase SDK для доступа к данным

firebase.database().ref('persons').child('personId');

...