Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an Uncompressor #49

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def hide?(thing)
def json_body
@json_body ||= begin
body = @request.body.read if @request.body
body.blank? ? {} : JSON.parse(body)
Uncompressor.uncompress(body.blank? ? {} : JSON.parse(body))
end
end

Expand Down
24 changes: 24 additions & 0 deletions lib/api/uncompressor.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Api
class Uncompressor
ID_MATCHER = /(\Aid\z|_id\z)/

def self.uncompress(body)
return body unless body.kind_of?(Hash)
body.each_with_object({}) do |(k, v), result|
result[k] =
case v
when Array
v.collect(&method(:uncompress))
when Hash
uncompress(v)
else
if k =~ ID_MATCHER
ApplicationRecord.uncompress_id(v)
else
v
end
end
end
end
end
end
44 changes: 44 additions & 0 deletions spec/lib/api/uncompressor_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
RSpec.describe Api::Uncompressor do
describe ".uncompress" do
it "converts compressed ids into uncompressed ids" do
actual = described_class.uncompress(:id => "1r1")
expected = {:id => 1_000_000_000_001}
expect(actual).to eq(expected)
end

it "will detect foreign key ids and uncompress them" do
actual = described_class.uncompress(:vm_or_template_id => "1r1")
expected = {:vm_or_template_id => 1_000_000_000_001}
expect(actual).to eq(expected)
end

it "will uncompress ids nested in arrays" do
actual = described_class.uncompress(:dialog_tabs => [{:id => "1r1"}])
expected = {:dialog_tabs => [{:id => 1_000_000_000_001}]}
expect(actual).to eq(expected)
end

it "will uncompress ids nested in hashes" do
actual = described_class.uncompress(:content => {:dialog_tabs => [{:id => "1r1"}]})
expected = {:content => {:dialog_tabs => [{:id => 1_000_000_000_001}]}}
expect(actual).to eq(expected)
end

it "will leave non-id attributes as-is" do
actual = described_class.uncompress(:foo => "bar")
expected = {:foo => "bar"}
expect(actual).to eq(expected)
end

it "will preserve the input" do
body = {:id => "1r1"}
expect { described_class.uncompress(body) }.not_to change { body }
end

it "can handle unexpected input" do
actual = described_class.uncompress(true)
expected = true
expect(actual).to eq(expected)
end
end
end