Sha256: ce40447b7f9b39427ec29f16f73d840e91bb8692b933d34efd332ac6990d0ff1

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module All3DP
  # Handle all calls to the API.
  class API
    class Error < StandardError; end
    class BadGatewayError < Error; end
    class GatewayTimeoutError < Error; end
    class ServiceUnavailableError < Error; end

    def create_configuration(items:)
      json = { items: items }
      response = json_post("#{BASE_URL}/configuration", json)

      JSON.parse(response_body(response))
    end

    private

    BASE_URL = "https://api.craftcloud3d.com"
    private_constant :BASE_URL

    def response_body(response)
      body = response.body.to_s.strip

      case response.code
      when "201" then body
      when "502" then raise BadGatewayError, body
      when "503" then raise ServiceUnavailableError, body
      when "504" then raise GatewayTimeoutError, body
      else raise Error, "Error #{response.code}: #{body.inspect}"
      end
    end

    def json_post(url, json)
      uri = URI.parse(url)
      request = Net::HTTP::Post.new(uri)
      request.content_type = "application/json; charset=UTF-8"
      request["use-model-urls"] = "true"
      request.body = JSON.dump(json)
      req_options = { use_ssl: uri.scheme == "https" }

      Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
        http.request(request)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
all3dp-1.0.1 lib/all3dp/api.rb
all3dp-1.0.0 lib/all3dp/api.rb