Skip to content

Commit ddfd5c7

Browse files
idleteaioquatix
authored andcommitted
Fix support for Workers KV
1 parent 5427e09 commit ddfd5c7

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

cloudflare.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
1616

1717
spec.required_ruby_version = ">= 2.5"
1818

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

2121
spec.add_development_dependency "async-rspec"
2222
spec.add_development_dependency "bundler"

lib/cloudflare/kv/namespaces.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
require_relative '../paginate'
77
require_relative '../representation'
8+
require_relative 'rest_wrapper'
89

910
module Cloudflare
1011
module KV
@@ -55,7 +56,8 @@ def write_value(name, value)
5556
private
5657

5758
def value_representation(name)
58-
self.with(Representation, path: "values/#{name}")
59+
@representation_class ||= Representation[RESTWrapper]
60+
self.with(@representation_class, path: "values/#{name}")
5961
end
6062
end
6163

lib/cloudflare/kv/rest_wrapper.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# frozen_string_literal: true
2+
3+
require 'json'
4+
5+
module Cloudflare
6+
module KV
7+
class RESTWrapper < Async::REST::Wrapper::Generic
8+
APPLICATION_OCTET_STREAM = 'application/octet-stream'
9+
APPLICATION_JSON = 'application/json'
10+
ACCEPT_HEADER = "#{APPLICATION_JSON}, #{APPLICATION_OCTET_STREAM}"
11+
12+
def prepare_request(payload, headers)
13+
headers['accept'] ||= ACCEPT_HEADER
14+
15+
if payload
16+
headers['content-type'] = APPLICATION_OCTET_STREAM
17+
::Protocol::HTTP::Body::Buffered.new([payload.to_s])
18+
end
19+
end
20+
21+
def parser_for(response)
22+
if response.headers['content-type'].start_with?(APPLICATION_OCTET_STREAM)
23+
OctetParser
24+
elsif response.headers['content-type'].start_with?(APPLICATION_JSON)
25+
JsonParser
26+
else
27+
Async::REST::Wrapper::Generic::Unsupported
28+
end
29+
end
30+
31+
class OctetParser < ::Protocol::HTTP::Body::Wrapper
32+
def join
33+
super
34+
end
35+
end
36+
37+
class JsonParser < ::Protocol::HTTP::Body::Wrapper
38+
def join
39+
JSON.parse(super, symbolize_names: true)
40+
end
41+
end
42+
end
43+
end
44+
end

0 commit comments

Comments
 (0)