Skip to content

Commit

Permalink
refactor: clear key when penalize method gets successful response
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Feb 6, 2024
1 parent 1479c80 commit 2133576
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,12 @@ export class Limiter implements LimiterStoreContract {
* Consume 1 request for a given key when the executed method throws
* an error.
*
* The method will throw an exception when all requests
* have been exhausted.
* - Check if all the requests have been exhausted. If yes, throw limiter
* error.
* - Otherwise, execute the provided callback.
* - Increment the requests counter, if provided callback throws an error and rethrow
* the error
* - Delete key, if the provided callback succeeds and return the results.
*/
async penalize<T>(key: string | number, callback: () => T | Promise<T>): Promise<T> {
const response = await this.get(key)
Expand All @@ -101,6 +105,7 @@ export class Limiter implements LimiterStoreContract {

try {
const result = await callback()
await this.delete(key)
return result
} catch (error) {
await this.increment(key)
Expand Down
4 changes: 3 additions & 1 deletion tests/limiter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,13 +216,15 @@ test.group('Limiter', () => {
})
}, 'Something went wrong')

assert.equal(await limiter.remaining('ip_localhost'), 1)

assert.isTrue(
await limiter.penalize('ip_localhost', () => {
return true
})
)

assert.equal(await limiter.remaining('ip_localhost'), 1)
assert.isNull(await limiter.get('ip_localhost'))
})

test('throw error via penalize when all requests has been exhausted', async ({ assert }) => {
Expand Down

0 comments on commit 2133576

Please sign in to comment.