Class: Cloudflare::KVNamespace

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

Instance Method Summary collapse

Constructor Details

#initialize(js) ⇒ KVNamespace

Returns a new instance of KVNamespace.



790
791
792
# File 'lib/homura/runtime.rb', line 790

def initialize(js)
  @js = js
end

Instance Method Details

#delete(key) ⇒ Object

Delete a key. Returns a JS Promise.



819
820
821
822
823
# File 'lib/homura/runtime.rb', line 819

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.



796
797
798
799
800
# File 'lib/homura/runtime.rb', line 796

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.



806
807
808
809
810
811
812
813
814
815
816
# File 'lib/homura/runtime.rb', line 806

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