Class: Tessa::RackUploadProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/tessa/rack_upload_proxy.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(*args) ⇒ Object



35
36
37
# File 'lib/tessa/rack_upload_proxy.rb', line 35

def self.call(*args)
  new.call(*args)
end

Instance Method Details

#call(env) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tessa/rack_upload_proxy.rb', line 4

def call(env)
  request = Rack::Request.new(env)
  ::ActiveStorage::Current.host ||= request.base_url

  # Call in to ActiveStorage to create a DirectUpload blob
  params = env['rack.request.form_hash']

  blob = ::ActiveStorage::Blob.create_before_direct_upload!({
    filename: params["name"],
    byte_size: params["size"],
    content_type: params["mime_type"],
    checksum: params["checksum"]
  })

  env['rack.session'][:tessa_upload_asset_ids] ||= []
  env['rack.session'][:tessa_upload_asset_ids] << blob.signed_id

  response = {
    asset_id: blob.signed_id,
    upload_url: blob.service_url_for_direct_upload,
    upload_method: 'PUT', # ActiveStorage is always PUT
    upload_headers: blob.service_headers_for_direct_upload
  }

  [200, {"Content-Type" => "application/json"}, [response.to_json]]
rescue Tessa::RequestFailed
  [500, {"Content-Type" => "application/json"}, [{ "error" => "Failed to retreive upload URL" }.to_json]]
rescue ActiveRecord::NotNullViolation => e
  [400, {"Content-Type" => "application/json"}, [{ "error" => e.message }.to_json]]
end