Last active
August 29, 2015 14:03
-
-
Save linhmtran168/83a645a26824fc87ca96 to your computer and use it in GitHub Desktop.
Custom Her Middleware to add additional pagination data to the response metadata
This file contains hidden or 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
| # 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