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.



729
730
731
# File 'lib/cloudflare_workers.rb', line 729

def initialize(js)
  @js = js
end

Instance Method Details

#delete(key) ⇒ Object

Delete a key. Returns a JS Promise.



758
759
760
761
762
# File 'lib/cloudflare_workers.rb', line 758

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.



735
736
737
738
739
# File 'lib/cloudflare_workers.rb', line 735

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.



745
746
747
748
749
750
751
752
753
754
755
# File 'lib/cloudflare_workers.rb', line 745

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