简体   繁体   中英

Cloud functions rate limiter, not returning data

I'm trying to build a rate limiter that saves timestamp to realtime database and returns object which has values from only last 60 seconds to eventually count them, however this returns null every single time, I can see the writes passing to the database, been at this for hours following example from Rate limiting for Google/Firebase cloud functions? but not having any luck.

exports.testRateLimiter = 
functions.https.onRequest(async (req, res) => {

    var ref = db.ref('rateLimiter/test');
    var time = Date.now()
    var timeStr = time.toString()
    ref.push(timeStr)
    var orderByVal = Date.now()-60000
    var orderByValStr = orderByVal.toString()
    ref.orderByKey().startAt(orderByValStr).once("value", function(snapshot) {
        console.log(snapshot.val());
    });

});

Calling the variable orderByValStr , would suggest you intending on using orderByValue() and not orderByKey() .

If you were using Callable Cloud Functions for Firebase , using the async/await syntax makes sense. However for HTTP Events Cloud Functions for Firebase , as you are using here, they are suited to using the Promises API.

exports.testRateLimiter = 
functions.https.onRequest((req, res) => {

    const ref = db.ref('rateLimiter/test');
    const time = Date.now()
    const timeStr = time.toString()
    ref.push(timeStr)

    const startTime = Date.now()-60000

    ref.orderByValue().startAt(startTime).once("value")
      .then(snapshot => {
          console.log(snapshot.numChildren()); // log children instead
          // do the thing
      })
      .catch(error => {
          if (!res.headerSent) {
              res.sendStatus(500);
          }
          console.log('Error: ', error);
      });

});

I'd consider making use of firebase-functions-rate-limiter as it handles clean up for you. I recommend looking through it's source code and learning what you can from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM