在Firebase实时数据库中实现对话流实现的不同目录访问权限

问题描述

我是node.js(firebase函数)和Dialogflow实现的新手,我想在其他目录中检索数据。首先是检查最近的商店,然后在其他目录中检查商店的库存,但是退货有问题。那么我该如何解决

app.intent('location_checking - yes',(conv)=> {
  var store= database.ref('store');
  var inventory = database.ref('inventory);
  var keystore=[];
  return store.orderByKey().on("child_added",function(snapshot){
    keystore.push(snapshot.key)
  })
  return inventory.child(keystore).on("value",function(snapshot){
    var tomato =snapshot.val().tomato;
    //and then check the nearest store with available stock
  })
})

解决方法

您有一些问题,其中一些是概念性的。

第一个是您正在使用on()和“ child_added”事件。但是由于这是在Intent Handler内发生的,该Intent Handler仅在用户执行某项操作时才触发,因此您也无法监听常规事件并对它们做出反应。相反,您可能应该将once()与“值”事件一起使用-因此您查询所需的值并使用它们。

第二,如果您正在执行任何异步操作(例如,需要回调处理程序的任何操作),则Intent Handler希望您返回Promise。这将需要对如何调用once()进行一些重组,以便它们返回Promise,并在.then()块中执行操作。由于您可以使用.then()将Promises链接在一起,因此可以通过这种方式进行多次呼叫。

我不确定按键排序将使您成为“最近的”商店,但是暂时我将忽略它来说明其余的代码。

因此您的代码部分可能类似于

return store.orderByKey().once("value")
  .then( snapshot => {
    // Handle the results
    // ...

    // Make the next query
    return inventory.child( childKey ).once("value");
  })
  .then( snapshot => {
    // Handle the inventory results
  });

您还可以通过将Intent Handler设为异步函数,然后在数据库调用中调用await来执行异步/等待操作。可能是这样的。

app.intent('location_checking - yes',async (conv) => {
  const store= database.ref('store');
  const inventory = database.ref('inventory);

  //...

  const storeSnapshot = await store.orderByKey().once("value");
  // Do something with the store snapshot

  const inventorySnapshot = await inventory.child( childKey ).once("value");
  // Do stuff with the inventory snapshot
})