Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(usage): setup timestamp by parameter #25

Merged
merged 1 commit into from
May 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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