Skip to content

Instantly share code, notes, and snippets.

@linhmtran168
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save linhmtran168/83a645a26824fc87ca96 to your computer and use it in GitHub Desktop.

Select an option

Save linhmtran168/83a645a26824fc87ca96 to your computer and use it in GitHub Desktop.
Custom Her Middleware to add additional pagination data to the response metadata
# lib/custome_parse_json
# Custome middleware to include pagination data
class CustomParseJSON < Her::Middleware::ParseJSON
# Parse the response body
#
# @param [String] body The response body
# @param [Hash] header the respone header
# @return [Mixed] the parsed response
# @private
def parse(body, header=nil)
json = parse_json(body)
errors = json.delete(:errors) || {}
metadata = json.delete(:metadata) || {}
data = {
:data => json,
:errors => errors,
:metadata => metadata
}
# Add the pagination data to the metadata
if header && header['total']
data[:metadata].merge total: header['total']
end
data
end
# This method is triggered when the response has been received. It modifies
# the value of `env[:body]`.
#
# @param [Hash] env The response environment
# @private
def on_complete(env)
env[:body] = case env[:satus]
when 204
parse('{}')
else
parse(env[:body], env[:response_headers])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment