Module: UserapiAi::HTTP
- Included in:
- Client
- Defined in:
- lib/userapi/http.rb
Instance Method Summary collapse
- #conn(multipart: false) ⇒ Object
- #headers ⇒ Object
- #json_get(path:, parameters: {}) ⇒ Object
- #json_post(path:, parameters:) ⇒ Object
- #multipart_parameters(parameters) ⇒ Object
-
#to_json(string) ⇒ Object
private.
- #uri(path:, parameters: {}) ⇒ Object
Instance Method Details
#conn(multipart: false) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/userapi/http.rb', line 32 def conn(multipart: false) Faraday.new do |f| f.[:timeout] = UserapiAi.configuration.request_timeout f.request(:multipart) if multipart end end |
#headers ⇒ Object
45 46 47 48 49 50 |
# File 'lib/userapi/http.rb', line 45 def headers { "Content-Type" => "application/json", "api-key" => UserapiAi.configuration.access_token }.merge(UserapiAi.configuration.extra_headers) end |
#json_get(path:, parameters: {}) ⇒ Object
3 4 5 6 7 |
# File 'lib/userapi/http.rb', line 3 def json_get(path:, parameters: {}) to_json(conn.get(uri(path: path, parameters: parameters)) do |req| req.headers = headers end&.body) end |
#json_post(path:, parameters:) ⇒ Object
9 10 11 12 13 14 |
# File 'lib/userapi/http.rb', line 9 def json_post(path:, parameters:) to_json(conn.post(uri(path: path)) do |req| req.headers = headers req.body = parameters.to_json end&.body) end |
#multipart_parameters(parameters) ⇒ Object
52 53 54 55 56 57 58 59 60 61 |
# File 'lib/userapi/http.rb', line 52 def multipart_parameters(parameters) parameters&.transform_values do |value| next value unless value.is_a?(File) # Doesn't seem like Midjourney needs mime_type yet, so not worth # the library to figure this out. Hence the empty string # as the second argument. Faraday::UploadIO.new(value, "", value.path) end end |
#to_json(string) ⇒ Object
private
18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/userapi/http.rb', line 18 def to_json(string) return unless string json = JSON.parse(string) if json["status"] == false and json.has_key?("error") raise StandardError.new json["error"] else json end rescue JSON::ParserError # Convert a multiline string of JSON objects to a JSON array. JSON.parse(string.gsub("}\n{", "},{").prepend("[").concat("]")) end |
#uri(path:, parameters: {}) ⇒ Object
39 40 41 42 43 |
# File 'lib/userapi/http.rb', line 39 def uri(path:, parameters: {}) str = "#{UserapiAi.configuration.uri_base}/#{UserapiAi.configuration.service}/#{UserapiAi.configuration.api_version}/#{path}" str += "?" + URI.encode_www_form(parameters) unless parameters.empty? str end |