Skip to content

Commit

Permalink
chore(usage): setup timestamp by parameter (#25)
Browse files Browse the repository at this point in the history
better for testing purpose
  • Loading branch information
Kikobeats authored May 28, 2024
1 parent 7f85918 commit d90c7af
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/usage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module.exports = ({ plans, keys, redis, stats, prefix, serialize, deserialize })
* @param {Object} options - The options for creating a plan.
* @param {number} [options.quantity=1] - The quantity to increment.
* @param {boolean} [options.throwError=true] - Throw an error if the key does not exist.
* @param {number} [options.timestamp=Date.now()] - The timestamp to use for the increment.
*
* @returns {Promise<{limit: number, remaining: number, reset: number, pending: Promise<void>}>}
*
Expand All @@ -25,21 +26,19 @@ module.exports = ({ plans, keys, redis, stats, prefix, serialize, deserialize })
* // }
*
*/
const increment = async (keyValue, { quantity = 1, throwError = true } = {}) => {
const increment = async (keyValue, { timestamp = Date.now(), quantity = 1, throwError = true } = {}) => {
const key = await keys.retrieve(keyValue, { throwError })
const plan = await plans.retrieve(key.plan, { throwError })

let usage = await deserialize(await redis.get(prefixKey(keyValue)))
const now = Date.now()

if (usage === null) {
usage = {
count: Math.min(quantity, plan.limit),
reset: now + ms(plan.period)
reset: timestamp + ms(plan.period)
}
} else if (now > usage.reset) {
} else if (timestamp > usage.reset) {
usage.count = quantity
usage.reset = now + ms(plan.period)
usage.reset = timestamp + ms(plan.period)
} else {
if (usage.count < plan.limit) {
usage.count = Math.min(usage.count + quantity, plan.limit)
Expand Down

0 comments on commit d90c7af

Please sign in to comment.