Sha256: 12d084a0acfed1398160ae4a2825d717c14c36d8ea6cc35ca0a6a57bd41f3ff1

Contents?: true

Size: 1.9 KB

Versions: 5

Compression:

Stored size: 1.9 KB

Contents

# frozen_string_literal: true

module OpenRecycling
  module Documents
    class Uploads < OpenRecycling::Resource
      only :create, :all

      def initialize(base_url: nil, jwt_token: nil)
        super(
          root_node_singular: "upload",
          root_node_plural: "uploads",
          api_url: "#{base_url}/uploads",
          jwt_token: jwt_token
        )
      end

      def create(file_path:, mime_type:, organization_id:)
        uri = URI(api_url)

        # Prepare the file and boundary
        boundary = "----Upload#{rand(1000000)}"
        file = File.open(file_path, 'rb')
        file_content = file.read

        # Prepare multipart body
        post_body = []
        post_body << "--#{boundary}\r\n"
        post_body << "Content-Disposition: form-data; name=\"upload[file]\"; filename=\"#{File.basename(file_path)}\"\r\n"
        post_body << "Content-Type: #{mime_type}\r\n\r\n"
        post_body << file_content
        post_body << "\r\n"

        # Add the `upload[organizationId]` part
        post_body << "--#{boundary}\r\n"
        post_body << "Content-Disposition: form-data; name=\"upload[organizationId]\"\r\n\r\n"
        post_body << organization_id.to_s
        post_body << "\r\n"

        post_body << "--#{boundary}--\r\n"

        # Create and send the POST request
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = (uri.scheme == 'https')

        request = Net::HTTP::Post.new(uri.path)
        request['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
        request["Authorization"] = "Bearer #{jwt_token}"
        request["Accept"] = "application/json"
        request.body = post_body.join

        # Execute the request and get the response
        response = http.request(request)

        if response.is_a?(Net::HTTPSuccess)
          parse_resource(response.body)
        else
          handle_error(response)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
open_recycling-0.0.7 lib/open_recycling/documents/uploads.rb
open_recycling-0.0.6 lib/open_recycling/documents/uploads.rb
open_recycling-0.0.5 lib/open_recycling/documents/uploads.rb
open_recycling-0.0.4 lib/open_recycling/documents/uploads.rb
open_recycling-0.0.3 lib/open_recycling/documents/uploads.rb