Skip to content

Commit

Permalink
Handling rate limits
Browse files Browse the repository at this point in the history
  • Loading branch information
danrowden committed Oct 29, 2024
1 parent 624cbc5 commit a99662d
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## v0.2.0 - Oct 29, 2024

Added rate limit handling with `RateLimitError`.

## v0.1.2 - Aug 16, 2024

Support for resetting contact properties with `nil`.
Expand Down
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
loops_sdk (0.1.0)
loops_sdk (0.2.0)
faraday

GEM
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ rescue LoopsSdk::APIError => e
end
```

## Handling rate limits

You can use the check for rate limit issues with your requests.

You can access details about the rate limits from the `limit` and `remaining` attributes.

```ruby
begin

response = LoopsSdk::Contacts.update(
email: "[email protected]"
)

render json: response

rescue LoopsSdk::RateLimitError => e
Rails.logger.error("Rate limit exceeded (#{e.limit} requests per second)")
# Code here to re-try this request
rescue LoopsSdk::APIError => e
# Handle other errors
end
```

## Default contact properties

Each contact in Loops has a set of default properties. These will always be returned in API results.
Expand Down
16 changes: 14 additions & 2 deletions lib/loops_sdk/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ def handle_response(response)
case response.status
when 200
JSON.parse(response.body)
when 429
limit = response.headers["x-ratelimit-limit"]
remaining = response.headers["x-ratelimit-remaining"]
raise RateLimitError.new(limit, remaining)
when 400, 404, 405, 409, 500
raise APIError.new(response.status, response.body)
else
Expand All @@ -25,8 +29,16 @@ def make_request(method, path, params = {}, body = nil)
end
end

# The `APIError` class in Ruby represents an error that occurs during an API request with specific
# status and response body information.
class RateLimitError < StandardError
attr_reader :limit, :remaining

def initialize(limit, remaining)
@limit = limit
@remaining = remaining
super("Rate limit of #{limit} requests per second exceeded.")
end
end

class APIError < StandardError
attr_reader :status, :body

Expand Down
2 changes: 1 addition & 1 deletion lib/loops_sdk/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module LoopsSdk
VERSION = "0.1.2"
VERSION = "0.2.0"
end

0 comments on commit a99662d

Please sign in to comment.