Skip to content

Commit

Permalink
feat: add try function
Browse files Browse the repository at this point in the history
  • Loading branch information
0OZ committed Jun 24, 2024
1 parent 4748279 commit 3800699
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/main/kotlin/io.evest.simpleratelimiter/Option.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package io.evest.simpleratelimiter

data class Option<T>(val some: T, val exception: Exception? = null)
9 changes: 9 additions & 0 deletions src/main/kotlin/io.evest.simpleratelimiter/RateLimiter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,13 @@ object RateLimiter {
if (exhausted)
throw RateLimitException("Rate limit exceeded for key: $key")
}

fun <T> T.tryBucket(
key: String,
maxCalls: Int = 1,
per: Duration = Duration.ofSeconds(defaultMinWait),
): Option<T> = when (BucketHandler.count(key, maxCalls, per)) {
true -> Option(this, RateLimitException("Rate limit exceeded for key: $key"))
false -> Option(this)
}
}

0 comments on commit 3800699

Please sign in to comment.