Class: Cloudflare::KVNamespace

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

Instance Method Summary collapse

Constructor Details

#initialize(js) ⇒ KVNamespace

Returns a new instance of KVNamespace.



702
703
704
# File 'lib/cloudflare_workers.rb', line 702

def initialize(js)
  @js = js
end

Instance Method Details

#delete(key) ⇒ Object

Delete a key. Returns a JS Promise.



731
732
733
734
735
# File 'lib/cloudflare_workers.rb', line 731

def delete(key)
  js_kv = @js
  err_cls = Cloudflare::KVError
  `#{js_kv}.delete(#{key}).catch(function(e) { #{Kernel}.$raise(#{err_cls}.$new(e.message || String(e), Opal.hash({binding_type: 'KV', operation: 'delete'}))); })`
end

#get(key) ⇒ Object

KV#get returns a JS Promise resolving to a String or nil. In normal Sinatra app code, auto-await usually hides that Promise.



708
709
710
711
712
# File 'lib/cloudflare_workers.rb', line 708

def get(key)
  js_kv = @js
  err_cls = Cloudflare::KVError
  `#{js_kv}.get(#{key}, "text").then(function(v) { return v == null ? nil : v; }).catch(function(e) { #{Kernel}.$raise(#{err_cls}.$new(e.message || String(e), Opal.hash({binding_type: 'KV', operation: 'get'}))); })`
end

#put(key, value, expiration_ttl: nil) ⇒ Object

Put a value. ‘expiration_ttl:` (seconds) maps to the Workers KV `expirationTtl` option so callers can set TTLs without reaching for backticks. Returns a JS Promise; common route/helper call sites are auto-awaited during the build.



718
719
720
721
722
723
724
725
726
727
728
# File 'lib/cloudflare_workers.rb', line 718

def put(key, value, expiration_ttl: nil)
  js_kv = @js
  err_cls = Cloudflare::KVError
  ttl = expiration_ttl
  if ttl.nil?
    `#{js_kv}.put(#{key}, #{value}).catch(function(e) { #{Kernel}.$raise(#{err_cls}.$new(e.message || String(e), Opal.hash({binding_type: 'KV', operation: 'put'}))); })`
  else
    ttl_int = ttl.to_i
    `#{js_kv}.put(#{key}, #{value}, { expirationTtl: #{ttl_int} }).catch(function(e) { #{Kernel}.$raise(#{err_cls}.$new(e.message || String(e), Opal.hash({binding_type: 'KV', operation: 'put'}))); })`
  end
end