Skip to content

Commit

Permalink
Refactoring; simplify http_json/responder
Browse files Browse the repository at this point in the history
  • Loading branch information
JonJagger committed Jan 15, 2020
1 parent f63e2cd commit a80a3b1
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions app/services/http_json/responder.rb
Expand Up @@ -16,31 +16,27 @@ def initialize(requester, exception_class)
def get(path, args)
response = @requester.get(path, args)
unpacked(response.body, path.to_s)
rescue => error
fail @exception_class, error.message
end

# - - - - - - - - - - - - - - - - - - - - -

def post(path, args)
response = @requester.post(path, args)
unpacked(response.body, path.to_s)
rescue => error
fail @exception_class, error.message
end

private

def unpacked(body, path)
json = json_parse(body)
unless json.is_a?(Hash)
fail error_msg(body, 'is not JSON Hash')
throw error_msg(body, 'is not JSON Hash')
end
if json.has_key?('exception')
fail JSON.pretty_generate(json['exception'])
throw JSON.pretty_generate(json['exception'])
end
unless json.has_key?(path)
fail error_msg(body, "has no key for '#{path}'")
throw error_msg(body, "has no key for '#{path}'")
end
json[path]
end
Expand All @@ -50,7 +46,7 @@ def unpacked(body, path)
def json_parse(body)
JSON.parse(body)
rescue JSON::ParserError
fail error_msg(body, 'is not JSON')
throw error_msg(body, 'is not JSON')
end

# - - - - - - - - - - - - - - - - - - - - -
Expand All @@ -59,6 +55,12 @@ def error_msg(body, text)
"http response.body #{text}:#{body}"
end

# - - - - - - - - - - - - - - - - - - - - -

def throw(message)
fail @exception_class, message
end

end

end

0 comments on commit a80a3b1

Please sign in to comment.