lib/shodanz/apis/utils.rb in shodanz-2.0.2 vs lib/shodanz/apis/utils.rb in shodanz-2.0.3

- old
+ new

@@ -76,65 +76,68 @@ raise Shodanz::Errors::InvalidKey if json['error'].casecmp(INVALIDKEY) >= 0 end return json end - def getter(path, one_shot=false, **params) + def getter(path, **params) # param keys should all be strings params = params.transform_keys(&:to_s) # build up url string based on special params - url = "#{@url}#{path}?key=#{@key}" + url = "/#{path}?key=#{@key}" # special params params.each do |param,value| next if value.is_a?(String) && value.empty? value = URI.encode_www_form_component("#{value}") url += "&#{param}=#{value}" end - resp = @internet.get(url) + resp = @client.get(url) - # parse all lines in the response body as JSON - json = JSON.parse(resp.body.join) + if resp.success? + # parse all lines in the response body as JSON + json = JSON.parse(resp.body.join) - @internet.close if one_shot + handle_any_json_errors(json) - handle_any_json_errors(json) - - return json + return json + else + raise "Got response status #{resp.status}" + end ensure + @client.pool.close resp&.close - @internet = Async::HTTP::Internet.new if one_shot end def poster(path, one_shot=false, **params) # param keys should all be strings params = params.transform_keys(&:to_s) # make POST request to server - resp = @internet.post("#{@url}#{path}?key=#{@key}", params) + resp = @client.post("/#{path}?key=#{@key}", nil, JSON.dump(params)) - # parse all lines in the response body as JSON - json = JSON.parse(resp.body.join) + if resp.success? + json = JSON.parse(resp.body.join) - @internet.close if one_shot + handle_any_json_errors(json) - handle_any_json_errors(json) - - return json + return json + else + raise "Got response status #{resp.status}" + end ensure + @client.pool.close resp&.close - @internet = Async::HTTP::Internet.new if one_shot end def slurper(path, **params) # param keys should all be strings params = params.transform_keys(&:to_s) # check if limit if (limit = params.delete('limit')) counter = 0 end # make GET request to server - resp = @internet.get("#{@url}#{path}?key=#{@key}", params) + resp = @client.get("/#{path}?key=#{@key}", params) # read body line-by-line until resp.body.nil? || resp.body.empty? resp.body.read.each_line do |line| next if line.strip.empty? @@ -149,28 +152,28 @@ resp&.close end def async_get(path, **params) Async::Task.current.async do - getter(path, false, **params) + getter(path, **params) end end def sync_get(path, **params) Async do - getter(path, true, **params) + getter(path, **params) end.wait end def async_post(path, **params) Async::Task.current.async do - poster(path, false, **params) + poster(path, **params) end end def sync_post(path, **params) Async do - poster(path, true, **params) + poster(path, **params) end.wait end def async_slurp_stream(path, **params) Async::Task.current.async do