Skip to content

Commit

Permalink
Fix support for Workers KV
Browse files Browse the repository at this point in the history
  • Loading branch information
idletea authored and ioquatix committed Jun 14, 2021
1 parent 5427e09 commit ddfd5c7
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
2 changes: 1 addition & 1 deletion cloudflare.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Gem::Specification.new do |spec|

spec.required_ruby_version = ">= 2.5"

spec.add_dependency "async-rest", "~> 0.10.0"
spec.add_dependency "async-rest", "~> 0.12.3"

spec.add_development_dependency "async-rspec"
spec.add_development_dependency "bundler"
Expand Down
4 changes: 3 additions & 1 deletion lib/cloudflare/kv/namespaces.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

require_relative '../paginate'
require_relative '../representation'
require_relative 'rest_wrapper'

module Cloudflare
module KV
Expand Down Expand Up @@ -55,7 +56,8 @@ def write_value(name, value)
private

def value_representation(name)
self.with(Representation, path: "values/#{name}")
@representation_class ||= Representation[RESTWrapper]
self.with(@representation_class, path: "values/#{name}")
end
end

Expand Down
44 changes: 44 additions & 0 deletions lib/cloudflare/kv/rest_wrapper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

require 'json'

module Cloudflare
module KV
class RESTWrapper < Async::REST::Wrapper::Generic
APPLICATION_OCTET_STREAM = 'application/octet-stream'
APPLICATION_JSON = 'application/json'
ACCEPT_HEADER = "#{APPLICATION_JSON}, #{APPLICATION_OCTET_STREAM}"

def prepare_request(payload, headers)
headers['accept'] ||= ACCEPT_HEADER

if payload
headers['content-type'] = APPLICATION_OCTET_STREAM
::Protocol::HTTP::Body::Buffered.new([payload.to_s])
end
end

def parser_for(response)
if response.headers['content-type'].start_with?(APPLICATION_OCTET_STREAM)
OctetParser
elsif response.headers['content-type'].start_with?(APPLICATION_JSON)
JsonParser
else
Async::REST::Wrapper::Generic::Unsupported
end
end

class OctetParser < ::Protocol::HTTP::Body::Wrapper
def join
super
end
end

class JsonParser < ::Protocol::HTTP::Body::Wrapper
def join
JSON.parse(super, symbolize_names: true)
end
end
end
end
end

0 comments on commit ddfd5c7

Please sign in to comment.