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.



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

def initialize(js)
  @js = js
end

Instance Method Details

#delete(key) ⇒ Object

Delete a key. Returns a JS Promise.



738
739
740
741
742
# File 'lib/cloudflare_workers.rb', line 738

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.



715
716
717
718
719
# File 'lib/cloudflare_workers.rb', line 715

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.



725
726
727
728
729
730
731
732
733
734
735
# File 'lib/cloudflare_workers.rb', line 725

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