0

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());
    });

});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441

1 Answers1

1

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.

samthecodingman
  • 23,122
  • 4
  • 30
  • 54
  • Warning: While an `onRequest()` function is suited to using Promises for error handling, unlike other Cloud Functions, you can't use them to keep a function "alive" by simply returning the Promise. If `res.send()`, `res.end()`, `res.json()` or `res.sendStatus()` haven't been called in a timely manner, your Cloud Function may be terminated before completing. – samthecodingman Jan 22 '20 at 00:05
  • I have tried using firebase-functions-rate-limiter as the first option however when I try to deploy the functions while using this library it says the functions retrieved from this lib don't exist, I've tried variations with orderByValue as well but it didn't work for me previously, let me try this and will accept the answer if resolved, thank you! – Martin Dichtler Jan 22 '20 at 16:46