'Get the last document and rate limit the client to one write every 5 minutes in cloud firestore

I have these values stored in documents inside a collection:

{
  value: string,
  currValId: number,
  chosen: bool,
  requestTime: number, // the time the request is sent, in unix milliseconds
  userId: string       // user's uid
}

I am validating the requestTime field with this function:

function timeWithinReach(claimedTime){
  return request.resource.requestTime is number && 
  request.time - claimedTime < 5 * 1000;
}

Where the claimedTime is the requestTime the client sends, and I am basically comparing it to the request's time and tolerating a latency of 5 seconds in the process.

What I want to do is, in my security rules I want to get the last document from the current user and check if the requestTime from the current request is at least 5 minutes later from the last document, and only allow a write if that is the case.

Is my approach correct? If so, how may I get the requestTime from the last document? If my approach is wrong and I am misunderstanding things, what is the best way of accomplishing this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source