mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-26 01:33:22 +00:00
Raise errors on DFC requests
The simplified API was only returning the response body, not allowing us to inspect if an error occurred. Since an error should be an exception when communicating with a standardised protocol, we raise an error and keep our simple API.
This commit is contained in:
@@ -14,9 +14,12 @@ class DfcRequest
|
||||
end
|
||||
|
||||
def call(url, data = nil)
|
||||
response = request(url, data)
|
||||
begin
|
||||
response = request(url, data)
|
||||
rescue Faraday::UnauthorizedError, Faraday::ForbiddenError
|
||||
raise unless token_stale?
|
||||
|
||||
if response.status >= 400 && token_stale?
|
||||
# If access was denied and our token is stale then refresh and retry:
|
||||
refresh_access_token!
|
||||
response = request(url, data)
|
||||
end
|
||||
@@ -47,7 +50,10 @@ class DfcRequest
|
||||
'Content-Type' => 'application/json',
|
||||
'Authorization' => "Bearer #{@user.oidc_account.token}",
|
||||
}
|
||||
)
|
||||
) do |f|
|
||||
# Configure Faraday to raise errors on status 4xx and 5xx responses.
|
||||
f.response :raise_error
|
||||
end
|
||||
end
|
||||
|
||||
def only_public_connections(&)
|
||||
|
||||
@@ -40,11 +40,13 @@ RSpec.describe DfcRequest do
|
||||
|
||||
expect {
|
||||
api.call("http://example.net/api")
|
||||
}.to change {
|
||||
account.token
|
||||
}.and change {
|
||||
account.refresh_token
|
||||
}
|
||||
.to raise_error(Faraday::UnauthorizedError)
|
||||
.and change {
|
||||
account.token
|
||||
}.and change {
|
||||
account.refresh_token
|
||||
}
|
||||
end
|
||||
|
||||
it "doesn't try to refresh the token when it's still fresh" do
|
||||
@@ -53,7 +55,8 @@ RSpec.describe DfcRequest do
|
||||
|
||||
user.oidc_account.updated_at = 1.minute.ago
|
||||
|
||||
expect(api.call("http://example.net/api")).to eq ""
|
||||
expect { api.call("http://example.net/api") }
|
||||
.to raise_error(Faraday::UnauthorizedError)
|
||||
|
||||
# Trying to reach the OIDC server via network request to refresh the token
|
||||
# would raise errors because we didn't setup Webmock or VCR.
|
||||
|
||||
Reference in New Issue
Block a user