# 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:, issued_by_organization_id: nil) 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[issuedToOrganizationId]\"\r\n\r\n" post_body << organization_id.to_s post_body << "\r\n" if issued_by_organization_id # Add the `upload[issuedByOrganizationId]` part post_body << "--#{boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"upload[issuedByOrganizationId]\"\r\n\r\n" post_body << issued_by_organization_id.to_s post_body << "\r\n" end 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