Class: R2::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/r2/storage.rb

Overview

Storage layer responsible for communicating with Cloudflare R2.

Uses the aws-sdk-s3 gem with the S3-compatible endpoint provided by the application configuration.

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Storage

Initializes the storage with the configured credentials and bucket.

Parameters:



15
16
17
18
19
20
21
22
23
24
# File 'lib/r2/storage.rb', line 15

def initialize(config)
    @bucket = config.bucket
    @s3 = Aws::S3::Client.new(
        region: config.region,
        access_key_id: config.access_key_id,
        secret_access_key: config.secret_access_key,
        endpoint: config.endpoint,
        force_path_style: true
    )
end

Instance Method Details

#delete(key:) ⇒ Object

Deletes an object from the configured bucket.

The operation is considered successful when Cloudflare R2 completes the request without raising an error.

Parameters:

  • key (String)

    object key in the bucket

Raises:



51
52
53
54
55
56
57
58
# File 'lib/r2/storage.rb', line 51

def delete(key:)
    @s3.delete_object(
        bucket: @bucket,
        key: key
    )
rescue StandardError => e
    raise_storage_error(e)
end

#listArray<String>

Lists the objects stored in the configured bucket.

Returns:

  • (Array<String>)

    keys of the stored objects

Raises:



64
65
66
67
68
69
# File 'lib/r2/storage.rb', line 64

def list
    response = @s3.list_objects_v2(bucket: @bucket)
    response.contents.map(&:key)
rescue StandardError => e
    raise_storage_error(e)
end

#upload(key:, body:) ⇒ Object

Uploads an object to the configured bucket.

Receives content already prepared by the layer that uses the storage and delivers it to Cloudflare R2.

Parameters:

  • key (String)

    object key in the bucket

  • body (IO, String)

    content of the object to upload

Raises:



34
35
36
37
38
39
40
41
42
# File 'lib/r2/storage.rb', line 34

def upload(key:, body:)
    @s3.put_object(
        bucket: @bucket,
        key: key,
        body: body
    )
rescue StandardError => e
    raise_storage_error(e)
end