-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: automatically extract meta and dig into root key
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
require "faraday" | ||
|
||
module Scalingo | ||
class UnpackMiddleware < Faraday::Middleware | ||
def on_complete(env) | ||
# We only want to unpack the response for successful responses | ||
return unless env.response.success? | ||
|
||
# Only hash-like objects are relevant to "unpack" | ||
return unless env.body.is_a?(Hash) | ||
|
||
# Extract meta from response | ||
if env.body[:meta] | ||
env[:response_meta] = env.body.delete(:meta) | ||
end | ||
|
||
# Extract cursor-based pagination | ||
if env.body.key?(:next_cursor) | ||
env[:response_meta] = { | ||
cursor_pagination: { | ||
next_cursor: env.body.delete(:next_cursor), | ||
has_more: env.body.delete(:has_more) | ||
}.compact | ||
} | ||
end | ||
|
||
# Dig the root key if it's the only remaining key in the body | ||
env.body = env.body.values.first if env.body.size == 1 | ||
end | ||
end | ||
end | ||
|
||
Faraday::Response.register_middleware(unpack: Scalingo::UnpackMiddleware) |