如何在then语句中定义Firebase云功能触发器

时间:2018-07-25 21:30:34

标签: javascript firebase google-cloud-functions

我需要确保在定义firebase函数之前运行此代码,因为它取决于代码中设置的变量:

const hotelBedTimeouts = [];

var beds = db.ref('/beds');

// Initialise the bed timeout holder object
beds.once("value", function(snapshot){
  var hotels = snapshot.val();

  for (var i = 0; i < hotels.length; i++) {
    // push empty list to be filled with lists holding individual bed timeouts
    if(hotels[i]){
      hotelBedTimeouts.push([]);
      for(var j = 0; j < hotels[i].length; j++) {
        // this list will hold all timeouts for this bed
        hotelBedTimeouts[i].push({});
      }
    } else {
      hotelBedTimeouts.push(undefined);
    }
  }
});

建议在.then()调用后将此函数放在once()语句中。所以我尝试了这个:

const hotelBedTimeouts = [];

var beds = db.ref('/beds');

// Initialise the bed timeout holder object
beds.once("value", function(snapshot){
  var hotels = snapshot.val();

  for (var i = 0; i < hotels.length; i++) {
    // push empty list to be filled with lists holding individual bed timeouts
    if(hotels[i]){
      hotelBedTimeouts.push([]);
      for(var j = 0; j < hotels[i].length; j++) {
        // this list will hold all timeouts for this bed
        hotelBedTimeouts[i].push({});
      }
    } else {
      hotelBedTimeouts.push(undefined);
    }
  }
}).then( () => {
  // Frees a bed after a set amount of time
  exports.scheduleFreeBed = functions.database.ref('/beds/{hotelIndex}/{bedIndex}/email').onUpdate( (snapshot, context) => {
     // My code
});

不幸的是,这导致我的整个Firebase函数被删除:

$ firebase deploy --only functions

=== Deploying to 'company-23uzc'...

i  functions: deleting function scheduleFreeBed...
✔  functions[scheduleFreeBed]: Successful delete operation.

是否可以通过这种方式定义firebase函数?

如何确保firebase函数始终可以访问后端代码中定义的某些变量?

编辑:

这是我在道格·史蒂文森(Doug Stevenson)回答后的首次尝试:

const hotelBedTimeouts = [];
var beds = db.ref('/beds');
const promise = beds.once("value");

// Frees a bed after a set amount of time
exports.scheduleFreeBed = functions.database.ref('/beds/{hotelIndex}/{bedIndex}/email').onUpdate( (snapshot, context) => {

  promise.then( (snapshot) => {
      var hotels = snapshot.val();

      for (var i = 0; i < hotels.length; i++) {
        // push empty list to be filled with lists holding individual bed timeouts
        if(hotels[i]){
          hotelBedTimeouts.push([]);
          for(var j = 0; j < hotels[i].length; j++) {
            // this list will hold all timeouts for this bed
            hotelBedTimeouts[i].push({});
          }
        } else {
          hotelBedTimeouts.push(undefined);
        }
      }
    });

  var originalEmail = snapshot.after.val();
  var hotelIndex = context.params.hotelIndex;
  var bedIndex = context.params.bedIndex;
  if (originalEmail === -1) {
    clearTimeout(hotelBedTimeouts[hotelIndex][bedIndex].timeoutFunc); // clear current timeoutfunc
    return 0; // Do nothing
  }

  // replace old timeout function
  hotelBedTimeouts[hotelIndex][bedIndex].timeoutFunc = setTimeout(function () { // ERROR HERE
    var bedRef = admin.database().ref(`/beds/${hotelIndex}/${bedIndex}`);
    bedRef.once("value", function(bedSnap){
      var bed = bedSnap.val();
      var booked = bed.booked;
      if (!booked) {
        var currentEmail = bed.email;
        // Check if current bed/email is the same as originalEmail
        if (currentEmail === originalEmail) {
          bedSnap.child("email").ref.set(-1, function() {
            console.log("Freed bed");
          });
        }
      }
    });
  }, 300000); // 5 min timeout


  return 0;
});

仍然,似乎在执行函数时没有正确定义hotelBedTimeouts,请看以下错误:

TypeError: Cannot read property '15' of undefined

我已在代码中的注释中标记了此错误所在的行。

如何仍然不能定义列表?

1 个答案:

答案 0 :(得分:1)

Firebase CLI不支持这种类型的功能定义。取而代之的是,您应该在该函数的内部中启动初始工作,并在以后缓存结果,从而不必再次执行它。或者,您可以尝试开始这项工作,并保留一个希望该函数以后可以使用的承诺,例如:

const promise = doSomeInitialWork()  // returns a promise that resolves with the data

exports.scheduleFreeBed = functions.database.ref(...).onUpdate(change => {
    promise.then(results => {
        // work with the results of doSomeInitialWork() here
    })
})