lib/ai21/http.rb in ai21-0.1.0 vs lib/ai21/http.rb in ai21-0.2.0

- old
+ new

@@ -2,50 +2,60 @@ require "uri" require "net/http" require "openssl" require "json" -require "pry" module AI21 module HTTP include AI21::Helper def get(path) - url = URI("#{AI21.configuration.uri_base}#{AI21.configuration.api_version}#{path}") - http = http(url) - request = get_request(url) - body = http.request(request).read_body - camel_to_snake ::JSON.parse(body) + fetch(path, :get) end def post(path, body) - url = URI("#{AI21.configuration.uri_base}#{AI21.configuration.api_version}#{path}") + fetch(path, :post, body) + end + + def delete(path) + fetch(path, :delete) + end + + def fetch(path, method, body = nil) + url = url(path) http = http(url) - request = post_request(url, body) + request = request(url, method) + + request.body = body.to_json if body + body = http.request(request).read_body camel_to_snake ::JSON.parse(body) end - def get_request(url) - request = Net::HTTP::Get.new(url) - request["accept"] = "application/json" - request["Authorization"] = "Bearer #{AI21.configuration.access_token}" + def request(url, method) + request = Object.const_get("Net::HTTP::#{method.capitalize}").new(url) + request["accept"] = content_type + request["content-type"] = content_type + request["Authorization"] = authorization request end - def post_request(url, body) - request = Net::HTTP::Post.new(url) - request["accept"] = "application/json" - request["content-type"] = "application/json" - request["Authorization"] = "Bearer #{AI21.configuration.access_token}" - request.body = body.to_json - request + def url(path) + URI("#{AI21.configuration.uri_base}#{AI21.configuration.api_version}#{path}") end def http(url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http + end + + def authorization + "Bearer #{AI21.configuration.access_token}" + end + + def content_type + "application/json" end end end