A platform for community discussion. Free, open, simple.
DEV: Convert versioned JSON:API requests into service parameters
Loïc Guitautcbcbf8de7677
diff --git a/lib/json_api_kit/edition.rb b/lib/json_api_kit/edition.rbindex 1b0c942abb1..b0674f702b8 100644--- a/lib/json_api_kit/edition.rb+++ b/lib/json_api_kit/edition.rb@@ -22,6 +22,10 @@ module JsonApiKitdef removed_sorts = @removed_sorts ||= RemovedSorts.new(changes)+ def existing_values(resource:, id:)+ ExistingValues.for(changes, current: resource.current_values(id))+ end+privateattr_reader :changesdiff --git a/lib/json_api_kit/existing_values.rb b/lib/json_api_kit/existing_values.rbnew file mode 100644index 00000000000..bced8c65ce8--- /dev/null+++ b/lib/json_api_kit/existing_values.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++module JsonApiKit+ class ExistingValues+ ConversionFailure = Class.new(StandardError)++ module None+ class << self+ def after(_change) = self++ def fetch(_name) = yield+ end+ end++ def self.for(changes, current:)+ new(+ changes+ .reverse_each+ .each_with_object({}) do |change, boundaries|+ boundaries[change] = current+ current = Previous.new(change, current:)+ end,+ )+ end++ def initialize(boundaries)+ @boundaries = boundaries+ end++ def after(change) = boundaries.fetch(change)++ private++ attr_reader :boundaries+ end+enddiff --git a/lib/json_api_kit/existing_values/previous.rb b/lib/json_api_kit/existing_values/previous.rbnew file mode 100644index 00000000000..ead2f5bff97--- /dev/null+++ b/lib/json_api_kit/existing_values/previous.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++module JsonApiKit+ class ExistingValues+ class Previous+ def initialize(change, current:)+ @change = change+ @current = current+ @values = {}+ end++ def fetch(name)+ return current.fetch(name) unless change.affects?(name)+ values.merge!(previous_values(name)) unless values.key?(name)+ values.fetch(name).deep_dup+ end++ private++ attr_reader :change, :current, :values++ def previous_values(name)+ change.previous_attributes(current_attributes_for(name))+ rescue VersionChange::Converter::Failure => error+ raise ConversionFailure, error.message+ end++ def current_attributes_for(name)+ change.current_names(name).to_h { [it, current.fetch(it)] }+ end+ end+ end+enddiff --git a/lib/json_api_kit/glossary.rb b/lib/json_api_kit/glossary.rbindex 59e01c75b61..b8763b96970 100644--- a/lib/json_api_kit/glossary.rb+++ b/lib/json_api_kit/glossary.rb@@ -28,6 +28,8 @@ module JsonApiKitendclass BadValue < BadParameter+ attr_reader :names+def initialize(names, parameter: nil)@names = namessuper("This version cannot convert the value of #{names.join(", ")}.", parameter:)@@ -37,8 +39,6 @@ module JsonApiKitprivate- attr_reader :names-def arguments = [names]end@@ -50,14 +50,16 @@ module JsonApiKit@member_names = {}end- def declared_attributes(attributes)+ def declared_attributes(attributes, **options)attributes.each_key { declared_names(it) }rules.each_with_index.reduce(attributes) do |result, (rule, index)|- rule.declared_attributes(result)+ rule.declared_attributes(result, **options)rescue VersionChange::Converter::Failure => failureraise BadValue.new(member_names_before(failure.names, index))+ rescue VersionChange::Converter::Tuple::InvalidResult => failure+ raise failure.convert_names { member_names_before([it], index) }endenddiff --git a/lib/json_api_kit/glossary/casing_rule.rb b/lib/json_api_kit/glossary/casing_rule.rbindex 8885efee565..5187a7ba265 100644--- a/lib/json_api_kit/glossary/casing_rule.rb+++ b/lib/json_api_kit/glossary/casing_rule.rb@@ -8,7 +8,7 @@ module JsonApiKitMEMBER_NAMES = Hash.new { |cache, name| cache[name] = camel_case(name) }class << self- def declared_attributes(attributes) = attributes.transform_keys { declared_name(it) }+ def declared_attributes(attributes, **) = attributes.transform_keys { declared_name(it) }def declared_name(name)snake_case(name).tap { raise Correction.new(it) unless camel_case(it) == name }diff --git a/lib/json_api_kit/glossary/version_rule.rb b/lib/json_api_kit/glossary/version_rule.rbindex aef1f7e6ba8..ba66639a849 100644--- a/lib/json_api_kit/glossary/version_rule.rb+++ b/lib/json_api_kit/glossary/version_rule.rb@@ -7,12 +7,13 @@ module JsonApiKit@changes = changesend- def declared_attributes(attributes)+ def declared_attributes(attributes, existing: ExistingValues::None)changes.each_with_index.reduce(attributes) do |result, (change, index)|- change.current_attributes(result)- rescue VersionChange::Converter::Failure => failure+ change.current_attributes(result, existing: existing.after(change))+ rescue VersionChange::Converter::Failure,+ VersionChange::Converter::Tuple::InvalidResult => failureraise failure.convert_names { previous_names(it, changes: changes.take(index)) }endenddiff --git a/lib/json_api_kit/request/body.rb b/lib/json_api_kit/request/body.rbindex 38d794c5b5d..f6dbb3d327b 100644--- a/lib/json_api_kit/request/body.rb+++ b/lib/json_api_kit/request/body.rb@@ -21,6 +21,7 @@ module JsonApiKitenddelegate :invalid?, to: :contract+ delegate :parameters, :locations_for, to: :attributesdef to_h = document@@ -34,6 +35,8 @@ module JsonApiKitdelegate :glossary, to: :editiondef contract = @contract ||= Contract.new(document, type: glossary.member_type(type))++ def attributes = @attributes ||= Attributes.new(document, glossary:)endendenddiff --git a/lib/json_api_kit/request/body/attributes.rb b/lib/json_api_kit/request/body/attributes.rbnew file mode 100644index 00000000000..452331ded7d--- /dev/null+++ b/lib/json_api_kit/request/body/attributes.rb@@ -0,0 +1,75 @@+# frozen_string_literal: true++module JsonApiKit+ class Request+ class Body+ class Attributes+ def initialize(document, glossary:, existing: ExistingValues::None)+ @document = document+ @glossary = glossary+ @existing = existing+ end++ def parameters+ @parameters ||=+ glossary+ .declared_attributes(submitted_attributes.deep_dup, existing:)+ .transform_keys { it.value.to_sym }+ rescue Glossary::NotAMemberName => error+ raise ConversionError.new(error, location: error_location([error.raw]))+ rescue Glossary::BadValue => error+ raise ConversionError.new(error, location: error_location(error.names))+ rescue VersionChange::Converter::Tuple::InvalidResult => error+ raise unless error.up?+ raise ConversionError.new(+ Glossary::BadValue.new(error.names),+ location: error_location(error.names),+ )+ end++ def locations_for(parameter)+ origins.fetch(parameter.to_sym, [])+ rescue Glossary::NotAMemberName => error+ raise ConversionError.new(error, location: error_location([error.raw]))+ end++ private++ attr_reader :document, :glossary, :existing++ def resource_object = document.fetch("data")++ def submitted_attributes+ @submitted_attributes ||=+ resource_object+ .fetch("attributes", {})+ .to_h do |name, value|+ [Name::Field.new(value: name, type: resource_object.fetch("type")), value]+ end+ end++ def origins+ @origins ||=+ submitted_attributes+ .each_key+ .each_with_object({}) do |name, locations|+ glossary+ .declared_names(name)+ .each do |declared_name|+ (locations[declared_name.value.to_sym] ||= []) << location(name)+ end+ end+ .transform_values(&:freeze)+ end++ def location(name) = Location.new(document, ["data", "attributes", name.value])++ def error_location(names)+ names.uniq.filter_map { location(it) if submitted_attributes.key?(it) }.sole+ rescue Enumerable::SoleItemExpectedError+ Location.new(document, %w[data attributes])+ end+ end+ end+ end+enddiff --git a/lib/json_api_kit/request/body/conversion_error.rb b/lib/json_api_kit/request/body/conversion_error.rbnew file mode 100644index 00000000000..56341d11c68--- /dev/null+++ b/lib/json_api_kit/request/body/conversion_error.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++module JsonApiKit+ class Request+ class Body+ class ConversionError < BadRequest+ def initialize(error, location:)+ @error = error+ @location = location+ super(error.message)+ end++ delegate :title, :detail, to: :error++ def source = { pointer: location.nearest_existing.pointer }++ private++ attr_reader :error, :location+ end+ end+ end+enddiff --git a/lib/json_api_kit/resource.rb b/lib/json_api_kit/resource.rbindex d81c27941f3..163f30ef200 100644--- a/lib/json_api_kit/resource.rb+++ b/lib/json_api_kit/resource.rb@@ -2,6 +2,8 @@module JsonApiKitclass Resource+ UnreadableAttribute = Class.new(StandardError)+include Naminginclude Sortinginclude Filteringdiff --git a/lib/json_api_kit/resource/current_values.rb b/lib/json_api_kit/resource/current_values.rbnew file mode 100644index 00000000000..e834609eb31--- /dev/null+++ b/lib/json_api_kit/resource/current_values.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++module JsonApiKit+ class Resource+ class CurrentValues+ def initialize(resource, id:)+ @resource = resource+ @id = id+ @values = {}+ end++ def fetch(name)+ values.fetch(name) { values[name] = attribute_value(name) }.deep_dup+ end++ private++ attr_reader :resource, :id, :values++ delegate :guardian, :schema, to: :resource++ def record+ @record ||= resource.scope_for(guardian).find_by(schema.primary_key => id) or raise NotFound+ end++ def attribute_value(name)+ resource.attribute_value(name, record:)+ end+ end+ end+enddiff --git a/lib/json_api_kit/resource/fields.rb b/lib/json_api_kit/resource/fields.rbindex 5995963dff7..4e30820ae5e 100644--- a/lib/json_api_kit/resource/fields.rb+++ b/lib/json_api_kit/resource/fields.rb@@ -62,6 +62,18 @@ module JsonApiKitenddelegate :attribute_names, :relationships, :fields, :resolves?, to: :class++ def attribute_value(name, record:)+ unless name.type == type && attribute_names.include?(name.value)+ raise KeyError, "#{name} is not an attribute of #{type}."+ end+ fields([name.value], guardian:)+ .attributes+ .values_for(record)+ .fetch(name) do+ raise UnreadableAttribute, "The existing value of #{name} is not readable."+ end+ endendendenddiff --git a/lib/json_api_kit/resource/query_interface.rb b/lib/json_api_kit/resource/query_interface.rbindex b67e7af01c5..6598590b3af 100644--- a/lib/json_api_kit/resource/query_interface.rb+++ b/lib/json_api_kit/resource/query_interface.rb@@ -32,6 +32,8 @@ module JsonApiKitdelegate :scope_for, to: :classdelegate :default_sorts, to: :edition, private: true+ def current_values(id) = CurrentValues.new(self, id:)+def all(params = {}, scoped_to: nil)Query::Collection.new(self,diff --git a/lib/json_api_kit/version_change.rb b/lib/json_api_kit/version_change.rbindex 504b4faabaa..0e85d9218ba 100644--- a/lib/json_api_kit/version_change.rb+++ b/lib/json_api_kit/version_change.rb@@ -78,9 +78,13 @@ module JsonApiKitdef current_names(name) = transformations.current_names(current_type(name))- def current_attributes(attributes)- transformations.current_values(attributes.transform_keys { current_type(it) })- rescue Converter::Failure => failure+ def affects?(name)+ type_renames.affects?(Name::Type.new(value: name.type)) || transformations.affects?(name)+ end++ def current_attributes(attributes, existing: ExistingValues::None)+ transformations.current_values(attributes.transform_keys { current_type(it) }, existing:)+ rescue Converter::Failure, Converter::Tuple::InvalidResult => failureraise failure.convert_names { previous_type(it) }enddiff --git a/lib/json_api_kit/version_change/converter/tuple.rb b/lib/json_api_kit/version_change/converter/tuple.rbindex e53c6ab6fde..8f1ce833c38 100644--- a/lib/json_api_kit/version_change/converter/tuple.rb+++ b/lib/json_api_kit/version_change/converter/tuple.rb@@ -4,6 +4,24 @@ module JsonApiKitclass VersionChangeclass Converterclass Tuple < Converter+ class InvalidResult < ArgumentError+ attr_reader :names++ def initialize(direction, names, message)+ @direction = direction+ @names = names+ super(message)+ end++ def up? = direction == :up++ def convert_names(&) = self.class.new(direction, names.flat_map(&).uniq, message)++ private++ attr_reader :direction+ end+def initialize(direction, callable, names, to:)@destinations = tosuper(direction, callable, names)@@ -12,10 +30,13 @@ module JsonApiKitdef call(...)Array(super).tap do |values|next if values.size == destinations.size- raise ArgumentError,- "#{direction} converter for #{names.join(", ")} must return " \- "#{destinations.size} #{"value".pluralize(destinations.size)} " \- "(#{destinations.join(", ")}). It returned #{values.size}."+ raise InvalidResult.new(+ direction,+ names,+ "#{direction} converter for #{names.join(", ")} must return " \+ "#{destinations.size} #{"value".pluralize(destinations.size)} " \+ "(#{destinations.join(", ")}). It returned #{values.size}.",+ )endenddiff --git a/lib/json_api_kit/version_change/merge.rb b/lib/json_api_kit/version_change/merge.rbindex 4bbbe42c251..ad993845219 100644--- a/lib/json_api_kit/version_change/merge.rb+++ b/lib/json_api_kit/version_change/merge.rb@@ -6,11 +6,25 @@ module JsonApiKitData.define(:from, :to, :up, :down) dodef current_names = [to]- def current_pairs(attributes) = [[to, up.call(*attributes.values_at(*from))]]+ def current_pairs(attributes, existing: ExistingValues::None)+ [[to, up.call(*complete(attributes, existing).values_at(*from))]]+ enddef previous_names = from- def previous_pairs(attributes) = from.zip(down.call(attributes.fetch(to)))+ def previous_pairs(attributes) = source_pairs(attributes.fetch(to))++ private++ def source_pairs(value) = from.zip(down.call(value))++ def complete(attributes, existing)+ return attributes if from.all? { attributes.key?(it) }+ current = existing.fetch(to) { return attributes }+ source_pairs(current).to_h.merge(attributes)+ rescue Converter::Failure => error+ raise ExistingValues::ConversionFailure, error.message+ endendendenddiff --git a/lib/json_api_kit/version_change/name_changes.rb b/lib/json_api_kit/version_change/name_changes.rbindex 31304821042..ee6b8880aa0 100644--- a/lib/json_api_kit/version_change/name_changes.rb+++ b/lib/json_api_kit/version_change/name_changes.rb@@ -16,6 +16,8 @@ module JsonApiKitdef previous_names(name) = downward[name].previous_names+ def affects?(name) = upward.key?(name)+def verify!duplicate_name(&:previous_names).try { raise Conflict, "changes #{it} twice." }duplicate_name(&:current_names).try { raise Conflict, "changes two names into #{it}." }diff --git a/lib/json_api_kit/version_change/pass_through.rb b/lib/json_api_kit/version_change/pass_through.rbindex afe57668c90..3a7d8382bb6 100644--- a/lib/json_api_kit/version_change/pass_through.rb+++ b/lib/json_api_kit/version_change/pass_through.rb@@ -6,7 +6,7 @@ module JsonApiKitData.define(:name) dodef current_names = [name]- def current_pairs(attributes) = [[name, attributes[name]]]+ def current_pairs(attributes, **) = [[name, attributes[name]]]def previous_names = [name]diff --git a/lib/json_api_kit/version_change/rename.rb b/lib/json_api_kit/version_change/rename.rbindex 9033bf1d95e..6e1a5615b37 100644--- a/lib/json_api_kit/version_change/rename.rb+++ b/lib/json_api_kit/version_change/rename.rb@@ -6,7 +6,7 @@ module JsonApiKitData.define(:from, :to, :up, :down) dodef current_names = [to]- def current_pairs(attributes) = [[to, up.call(attributes[from])]]+ def current_pairs(attributes, **) = [[to, up.call(attributes[from])]]def previous_names = [from]diff --git a/lib/json_api_kit/version_change/split.rb b/lib/json_api_kit/version_change/split.rbindex 4ad33e2ee52..ff43ec7e54d 100644--- a/lib/json_api_kit/version_change/split.rb+++ b/lib/json_api_kit/version_change/split.rb@@ -6,7 +6,7 @@ module JsonApiKitData.define(:from, :to, :up, :down) dodef current_names = to- def current_pairs(attributes) = to.zip(up.call(attributes.fetch(from)))+ def current_pairs(attributes, **) = to.zip(up.call(attributes.fetch(from)))def previous_names = [from]diff --git a/lib/json_api_kit/version_change/transformations.rb b/lib/json_api_kit/version_change/transformations.rbindex 2d8c5b7e035..f743ec01696 100644--- a/lib/json_api_kit/version_change/transformations.rb+++ b/lib/json_api_kit/version_change/transformations.rb@@ -3,8 +3,8 @@module JsonApiKitclass VersionChangeclass Transformations < NameChanges- def current_values(attributes)- current_changes(attributes.keys).flat_map { it.current_pairs(attributes) }.to_h+ def current_values(attributes, existing: ExistingValues::None)+ current_changes(attributes.keys).flat_map { it.current_pairs(attributes, existing:) }.to_henddef previous_values(attributes)diff --git a/spec/integration/json_api_kit/body_parameters_spec.rb b/spec/integration/json_api_kit/body_parameters_spec.rbnew file mode 100644index 00000000000..7fe75096f37--- /dev/null+++ b/spec/integration/json_api_kit/body_parameters_spec.rb@@ -0,0 +1,293 @@+# frozen_string_literal: true++require_relative "support"++module JsonApiKitSpec+ class ConvertedTopicsController < JsonApiKit::BaseController+ resource :topics++ def create+ render json: {+ meta: {+ parameters: request_body.parameters,+ original: request_body.to_h,+ },+ },+ content_type: JsonApiKit::MediaType::JSON_API+ end+ end++ class RenameInputHeading < JsonApiKit::VersionChange+ version "2026-09-01"+ description "Discussion headings become headlines."++ resource :discussion_threads do+ renamed_attribute from: :heading, to: :headline+ end+ end++ class ConvertTopicInputs < JsonApiKit::VersionChange+ version "2026-09-02"+ description "Discussion threads become topics with current attribute shapes."++ renamed_type from: :discussion_threads, to: :topics++ resource :topics do+ renamed_attribute from: :headline,+ to: :title,+ up: ->(title) { title&.strip },+ down: ->(title) { title }+ merged_attributes from: %i[width height],+ to: :dimensions,+ up: ->(width, height) { [Integer(width), Integer(height)] },+ down: ->(dimensions) { dimensions }+ split_attribute from: :size,+ to: %i[pixel_width pixel_height],+ up: ->(size) { size },+ down: ->(width, height) { [width, height] }+ end+ end+end++RSpec.describe JsonApiKitSpec::ConvertedTopicsController, type: :request do+ describe "#create" do+ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE.to_s }+ let(:path) { "/api/converted-topics" }+ let(:document) { { "data" => { "type" => "discussionThreads", "attributes" => attributes } } }+ let(:attributes) { { "heading" => " Hello ", "position" => "12" } }+ let(:parsed_body) { JSON.parse(response.body) }+ let(:parameters) { parsed_body.dig("meta", "parameters") }+ let(:version_changes) do+ JsonApiKit::VersionChanges.new(+ [JsonApiKitSpec::RenameInputHeading, JsonApiKitSpec::ConvertTopicInputs].map do+ it.new(__FILE__)+ end,+ )+ end++ before do+ freeze_time(Date.new(2026, 9, 3))+ allow(JsonApiKit::VersionChanges).to receive(:core).and_return(version_changes)+ Rails.application.routes.disable_clear_and_finalize = true+ Rails.application.routes.draw do+ post "/api/converted-topics" => "json_api_kit_spec/converted_topics#create"+ end+ Rails.application.routes.disable_clear_and_finalize = false+ post path,+ params: document.to_json,+ headers: {+ "HTTP_API_VERSION" => version,+ "CONTENT_TYPE" => JsonApiKit::MediaType::JSON_API,+ }+ end++ after { Rails.application.reload_routes! }++ shared_examples "an invalid attribute input" do+ it "reports the error in the original body", :aggregate_failures do+ expect(response).to have_http_status(:bad_request)+ expect(parsed_body.fetch("errors")).to contain_exactly(+ a_hash_including("status" => "400", "source" => { "pointer" => pointer }),+ )+ end+ end++ it "supplies current parameters after applying version changes", :aggregate_failures do+ expect(response).to have_http_status(:ok)+ expect(parameters).to eq("title" => "Hello", "position" => "12")+ end++ it "retains the original document" do+ expect(parsed_body.dig("meta", "original")).to eq(document)+ end++ context "when the client uses the current version" do+ let(:version) { "2026-09-02" }+ let(:document) { { "data" => { "type" => "topics", "attributes" => attributes } } }+ let(:attributes) { { "title" => " Hello ", "position" => "12" } }++ it "preserves values for service casting and validation" do+ expect(parameters).to eq(attributes)+ end+ end++ context "when attributes are omitted" do+ let(:document) { { "data" => { "type" => "discussionThreads" } } }++ it "supplies no parameters" do+ expect(parameters).to eq({})+ end+ end++ context "when the query selects response fields" do+ let(:path) { "#{super()}?fields[discussionThreads]=heading" }++ it "retains all submitted parameters" do+ expect(parameters).to eq("title" => "Hello", "position" => "12")+ end+ end++ context "when an attribute is explicitly null" do+ let(:attributes) { { "heading" => nil } }++ it "preserves the explicit null" do+ expect(parameters).to eq("title" => nil)+ end+ end++ context "when an attribute contains structured values" do+ let(:attributes) { { "settings" => { "keepCase" => [false, nil, { "someKey" => "12" }] } } }++ it "preserves the nested keys and values" do+ expect(parameters).to eq(attributes)+ end+ end++ context "when a version merges attributes" do+ let(:attributes) { { "width" => "640", "height" => "480" } }++ it "supplies the merged value" do+ expect(parameters).to eq("dimensions" => [640, 480])+ end+ end++ context "when a version splits an attribute" do+ let(:attributes) { { "size" => [640, 480] } }++ it "supplies each current attribute" do+ expect(parameters).to eq("pixel_width" => 640, "pixel_height" => 480)+ end+ end++ context "when a later converter rejects a renamed value" do+ let(:attributes) { { "heading" => 42 } }+ let(:pointer) { "/data/attributes/heading" }++ it_behaves_like "an invalid attribute input"+ end++ context "when a split receives too few values" do+ let(:attributes) { { "size" => [640] } }+ let(:pointer) { "/data/attributes/size" }++ it_behaves_like "an invalid attribute input"+ end++ context "when a split receives no values" do+ let(:attributes) { { "size" => [] } }+ let(:pointer) { "/data/attributes/size" }++ it_behaves_like "an invalid attribute input"+ end++ context "when a split receives too many values" do+ let(:attributes) { { "size" => [640, 480, 10] } }+ let(:pointer) { "/data/attributes/size" }++ it_behaves_like "an invalid attribute input"+ end++ context "when an earlier change renamed the invalid split input" do+ let(:attributes) { { "legacySize" => [640] } }+ let(:pointer) { "/data/attributes/legacySize" }+ let(:version_changes) do+ JsonApiKit::VersionChanges.new(+ [+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-01"+ description "Legacy sizes become sizes."++ resource(:discussion_threads) { renamed_attribute from: :legacy_size, to: :size }+ end+ .new(__FILE__),+ *super().to_a,+ ],+ )+ end++ it_behaves_like "an invalid attribute input"++ it "describes the submitted attribute" do+ expect(parsed_body.fetch("errors").sole.fetch("detail")).to eq(+ "This version cannot convert the value of legacySize.",+ )+ end+ end++ context "when a merge converter rejects supplied values" do+ let(:attributes) { { "width" => "bad", "height" => "480" } }+ let(:pointer) { "/data/attributes" }++ it_behaves_like "an invalid attribute input"+ end++ context "when only one merge source was supplied" do+ let(:attributes) { { "height" => "bad" } }+ let(:pointer) { "/data/attributes/height" }++ it_behaves_like "an invalid attribute input"+ end++ context "when a later converter rejects a merged value" do+ let(:attributes) { { "width" => "640", "height" => "0" } }+ let(:pointer) { "/data/attributes" }+ let(:version_changes) do+ JsonApiKit::VersionChanges.new(+ super().to_a ++ [+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-03"+ description "Dimensions become an aspect ratio."++ resource :topics do+ renamed_attribute from: :dimensions,+ to: :aspect_ratio,+ up: ->(dimensions) { Rational(*dimensions) },+ down: ->(ratio) { [ratio.numerator, ratio.denominator] }+ end+ end+ .new(__FILE__),+ ],+ )+ end++ it_behaves_like "an invalid attribute input"++ it "describes the original source attributes" do+ expect(parsed_body.fetch("errors").sole.fetch("detail")).to eq(+ "This version cannot convert the value of width, height.",+ )+ end+ end++ context "when the client supplies a name from a later version" do+ let(:attributes) { { "title" => "Hello" } }+ let(:pointer) { "/data/attributes/title" }++ it_behaves_like "an invalid attribute input"+ end++ context "when a name uses the wrong casing" do+ let(:attributes) { { "unknown_field" => "Hello" } }+ let(:pointer) { "/data/attributes/unknown_field" }++ it_behaves_like "an invalid attribute input"+ end++ context "when the invalid name contains pointer characters" do+ let(:attributes) { { "invalid/~Name" => "Hello" } }+ let(:pointer) { "/data/attributes/invalid~1~0Name" }++ it_behaves_like "an invalid attribute input"+ end++ context "when the attributes object is malformed" do+ let(:attributes) { [] }+ let(:pointer) { "/data/attributes" }++ it_behaves_like "an invalid attribute input"+ end+ end+enddiff --git a/spec/integration/json_api_kit/partial_conversions_spec.rb b/spec/integration/json_api_kit/partial_conversions_spec.rbnew file mode 100644index 00000000000..1d06c91b596--- /dev/null+++ b/spec/integration/json_api_kit/partial_conversions_spec.rb@@ -0,0 +1,285 @@+# frozen_string_literal: true++module JsonApiKitSpec+ class PartialImageResource < JsonApiKit::Resource+ model Topic+ type :images+ scope { |guardian| Topic.where(user_id: guardian.user.id) }++ attribute(:pixel_width) { it.posts_count }+ attribute(:pixel_height) { it.views }+ attribute(:caption) { it.title.split(":") }+ attribute(:unrelated) { raise "This attribute is not needed for conversion" }+ end++ class MergePartialImageFields < JsonApiKit::VersionChange+ version "2026-09-01"+ description "Image dimensions and captions become structured values."++ resource :pictures do+ merged_attributes from: %i[image_width image_height],+ to: :dimensions,+ up: ->(width, height) { [width, height] },+ down: ->(dimensions) { dimensions }+ merged_attributes from: %i[caption_left caption_right],+ to: :caption,+ up: ->(left, right) { [left, right] },+ down: ->(caption) { caption }+ end+ end++ class SplitPartialImageDimensions < JsonApiKit::VersionChange+ version "2026-09-02"+ description "Pictures become images with separate dimensions."++ renamed_type from: :pictures, to: :images++ resource :images do+ split_attribute from: :dimensions,+ to: %i[pixel_width pixel_height],+ up: ->(dimensions) { dimensions },+ down: ->(width, height) { [width, height] }+ renamed_attribute from: :unrelated,+ to: :unrelated_value,+ up: ->(value) { value },+ down: ->(_) { raise "Unrelated conversion" }+ end+ end+end++RSpec.describe "JSON:API partial attribute conversions" do+ subject(:converted) { edition.glossary.declared_attributes(attributes, existing:) }++ fab!(:author, :user)+ fab!(:topic) do+ Fabricate(+ :topic,+ user: author,+ title: "Left caption:Right caption",+ posts_count: 640,+ views: 480,+ )+ end++ let(:changes) do+ [JsonApiKitSpec::MergePartialImageFields, JsonApiKitSpec::SplitPartialImageDimensions].map do+ it.new(__FILE__)+ end+ end+ let(:edition) { JsonApiKit::Edition.new(changes) }+ let(:resource) { JsonApiKitSpec::PartialImageResource.new(guardian: author.guardian, edition:) }+ let(:existing) { edition.existing_values(resource:, id:) }+ let(:id) { topic.id }+ let(:image_width) { JsonApiKit::Name::Field.new(value: "imageWidth", type: "pictures") }+ let(:image_height) { image_width.with(value: "imageHeight") }+ let(:pixel_width) { JsonApiKit::Name::Field.new(value: "pixel_width", type: "images") }+ let(:pixel_height) { pixel_width.with(value: "pixel_height") }+ let(:caption_left) { image_width.with(value: "captionLeft") }+ let(:caption) { pixel_width.with(value: "caption") }+ let(:attributes) { { image_width => 800 } }+ let(:reads) { track_sql_queries { converted }.grep(/FROM "topics"/) }++ before { id }++ it "completes the merge through the later split and type rename" do+ expect(converted).to eq(pixel_width => 800, pixel_height => 480)+ end++ context "when only the second source is supplied" do+ let(:attributes) { { image_height => 600 } }++ it "preserves the first position" do+ expect(converted).to eq(pixel_width => 640, pixel_height => 600)+ end+ end++ context "when a source is explicitly null" do+ let(:attributes) { { image_width => nil } }++ it "overrides the existing value" do+ expect(converted).to eq(pixel_width => nil, pixel_height => 480)+ end+ end++ context "when every source is supplied" do+ let(:attributes) { super().merge(image_height => 600) }+ let(:id) { 0 }++ it "converts without an existing record" do+ expect(converted).to eq(pixel_width => 800, pixel_height => 600)+ end++ it "does not query the record" do+ expect(reads).to be_empty+ end+ end++ context "when no conversion source is supplied" do+ let(:previous_field) { image_width.with(value: "untouched") }+ let(:current_field) { pixel_width.with(value: "untouched") }+ let(:attributes) { { previous_field => false } }+ let(:id) { 0 }++ it "leaves the conversion groups untouched" do+ expect(converted).to eq(current_field => false)+ end++ it "does not query the record" do+ expect(reads).to be_empty+ end+ end++ context "when several groups need existing values" do+ let(:attributes) { super().merge(caption_left => "New") }++ it "completes each affected group" do+ expect(converted).to eq(+ pixel_width => 800,+ pixel_height => 480,+ caption => ["New", "Right caption"],+ )+ end++ it "loads the record once" do+ expect(reads).to contain_exactly(a_string_matching(/SELECT .*FROM "topics"/))+ end+ end++ context "when a later change also converts a destination value" do+ let(:canvas_width) { pixel_width.with(value: "canvas_width") }+ let(:attributes) { { image_height => 600 } }+ let(:changes) do+ super() ++ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :images do+ renamed_attribute from: :pixel_width,+ to: :canvas_width,+ up: ->(width) { width * 10 },+ down: ->(width) { width / 10 }+ end+ end+ .new(__FILE__),+ ]+ end+ let(:resource) do+ Class+ .new(JsonApiKit::Resource) do+ model Topic+ type :images+ attribute(:canvas_width) { it.posts_count * 10 }+ attribute(:pixel_height) { it.views }+ end+ .new(guardian: author.guardian, edition:)+ end++ it "recovers values through each later change" do+ expect(converted).to eq(canvas_width => 6400, pixel_height => 600)+ end+ end++ context "when a caller changes a current value" do+ let(:attributes) { { caption_left => "New" } }++ before { existing.after(changes.last).fetch(caption).clear }++ it "preserves the cached record value" do+ expect(converted).to eq(caption => ["New", "Right caption"])+ end+ end++ context "when the record is outside the resource scope" do+ let(:resource) do+ JsonApiKitSpec::PartialImageResource.new(guardian: Fabricate(:user).guardian, edition:)+ end++ it "refuses the lookup" do+ expect { converted }.to raise_error(JsonApiKit::NotFound)+ end+ end++ context "when the existing height is unreadable" do+ let(:readable) { ->(_guardian) { false } }+ let(:resource) do+ permission = readable+ Class+ .new(JsonApiKit::Resource) do+ model Topic+ type :images+ attribute(:pixel_width) { it.posts_count }+ attribute(:pixel_height, readable: permission) { it.views }+ end+ .new(guardian: author.guardian, edition:)+ end++ it "reports an unreadable attribute" do+ expect { converted }.to raise_error(JsonApiKit::Resource::UnreadableAttribute)+ end++ context "when readability depends on the record" do+ let(:readable) { ->(_guardian, record) { record.views < 100 } }++ it "reports an unreadable attribute" do+ expect { converted }.to raise_error(JsonApiKit::Resource::UnreadableAttribute)+ end+ end++ context "when every source is supplied" do+ let(:attributes) { super().merge(image_height => 600) }++ it "converts without reading existing values" do+ expect(converted).to eq(pixel_width => 800, pixel_height => 600)+ end+ end+ end++ context "when a down converter modifies a current value" do+ let(:attributes) { { caption_left => "New" } }+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :pictures do+ merged_attributes from: %i[caption_left caption_right],+ to: :caption,+ up: ->(left, right) { [left, right] },+ down: ->(caption) { caption.reverse! }+ end+ end+ .new(__FILE__),+ super().last,+ ]+ end++ before { converted }++ it "preserves the current value" do+ expect(existing.after(changes.last).fetch(caption)).to eq(["Left caption", "Right caption"])+ end+ end++ context "when existing values cannot be converted to the earlier version" do+ let(:changes) do+ [+ super().first,+ Class+ .new(JsonApiKit::VersionChange) do+ renamed_type from: :pictures, to: :images++ resource :images do+ split_attribute from: :dimensions,+ to: %i[pixel_width pixel_height],+ up: ->(dimensions) { dimensions },+ down: ->(*) { raise ArgumentError, "Cannot reconstruct dimensions" }+ end+ end+ .new(__FILE__),+ ]+ end++ it "reports an existing-value conversion failure" do+ expect { converted }.to raise_error(JsonApiKit::ExistingValues::ConversionFailure)+ end+ end+enddiff --git a/spec/lib/json_api_kit/existing_values_spec.rb b/spec/lib/json_api_kit/existing_values_spec.rbnew file mode 100644index 00000000000..51cce4fb9c6--- /dev/null+++ b/spec/lib/json_api_kit/existing_values_spec.rb@@ -0,0 +1,84 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::ExistingValues do+ subject(:values) { described_class.for(changes, current:) }++ let(:dimensions) { JsonApiKit::Name::Field.new(value: "dimensions", type: "images") }+ let(:width) { dimensions.with(value: "width") }+ let(:height) { dimensions.with(value: "height") }+ let(:earlier) { Class.new(JsonApiKit::VersionChange).new(__FILE__) }+ let(:later) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :images do+ split_attribute from: :dimensions,+ to: %i[width height],+ up: ->(dimensions) { dimensions },+ down: ->(width, height) { [width, height] }+ end+ end+ .new(__FILE__)+ end+ let(:changes) { [earlier, later] }+ let(:current) { { width => 640, height => nil } }++ describe "#after" do+ subject(:historical) { values.after(earlier) }++ it "reconstructs the value after that change" do+ expect(historical.fetch(dimensions)).to eq([640, nil])+ end++ context "when a caller changes a returned value" do+ before { historical.fetch(dimensions).clear }++ it "preserves the cached value" do+ expect(historical.fetch(dimensions)).to eq([640, nil])+ end+ end++ context "when a later change converts a value without renaming it" do+ let(:later) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :images do+ renamed_attribute from: :width,+ to: :width,+ up: ->(width) { width * 10 },+ down: ->(width) { width / 10 }+ end+ end+ .new(__FILE__)+ end++ it "applies the value conversion" do+ expect(historical.fetch(width)).to eq(64)+ end+ end++ context "when a later merge reconstructs several historical members" do+ let(:later) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :images do+ merged_attributes from: %i[width height],+ to: :dimensions,+ up: ->(width, height) { [width, height] },+ down: ->(dimensions) { dimensions }+ end+ end+ .new(__FILE__)+ end+ let(:current) { { dimensions => [640, 480] } }++ before do+ historical.fetch(width)+ current.fetch(dimensions).replace([800, 600])+ end++ it "retains the other members from the same reconstruction" do+ expect(historical.fetch(height)).to eq(480)+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/glossary/casing_rule_spec.rb b/spec/lib/json_api_kit/glossary/casing_rule_spec.rbindex a2de4fd0020..2fbf88b56be 100644--- a/spec/lib/json_api_kit/glossary/casing_rule_spec.rb+++ b/spec/lib/json_api_kit/glossary/casing_rule_spec.rb@@ -6,7 +6,7 @@ RSpec.describe JsonApiKit::Glossary::CasingRule dolet(:value) { "createdAt" }describe "#declared_attributes" do- subject(:declared_attributes) { rule.declared_attributes(name => "2026-08-01") }+ subject(:declared_attributes) { rule.declared_attributes({ name => "2026-08-01" }) }it "returns the attributes with their names in snake case" doexpect(declared_attributes).to eq(name.with(value: "created_at") => "2026-08-01")diff --git a/spec/lib/json_api_kit/glossary/split_attributes_spec.rb b/spec/lib/json_api_kit/glossary/split_attributes_spec.rbindex ebc5d6ca6b1..73f9d85a247 100644--- a/spec/lib/json_api_kit/glossary/split_attributes_spec.rb+++ b/spec/lib/json_api_kit/glossary/split_attributes_spec.rb@@ -217,7 +217,9 @@ RSpec.describe JsonApiKit::Glossary dodescribe "#declared_attributes" doit "splits the source before merging its destinations" do- expect(glossary.declared_attributes(size => %w[640 480])).to eq(dimensions => [640, 480])+ expect(glossary.declared_attributes({ size => %w[640 480] })).to eq(+ dimensions => [640, 480],+ )endenddiff --git a/spec/lib/json_api_kit/request/body/attributes_spec.rb b/spec/lib/json_api_kit/request/body/attributes_spec.rbnew file mode 100644index 00000000000..6f26e117a21--- /dev/null+++ b/spec/lib/json_api_kit/request/body/attributes_spec.rb@@ -0,0 +1,202 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Request::Body::Attributes do+ subject(:input) { described_class.new(document, glossary:, existing:) }++ let(:document) { { "data" => { "type" => "topics", "attributes" => attributes } } }+ let(:attributes) { { "createdAt" => "2026-09-01", "settings" => { "keepCase" => [nil, "12"] } } }+ let(:glossary) { JsonApiKit::Edition.new(changes).glossary }+ let(:changes) { [] }+ let(:existing) { JsonApiKit::ExistingValues::None }++ describe "#parameters" do+ it "uses declared names for parameter keys" do+ expect(input.parameters).to eq(+ created_at: "2026-09-01",+ settings: {+ "keepCase" => [nil, "12"],+ },+ )+ end++ context "when the glossary raises an unexpected argument error" do+ before do+ allow(glossary).to receive(:declared_attributes).and_raise(+ ArgumentError,+ "Unexpected error",+ )+ end++ it "preserves the exception" do+ expect { input.parameters }.to raise_error(ArgumentError, "Unexpected error")+ end+ end++ context "when a converter mutates its input" do+ let(:attributes) { { "words" => %w[Hello world] } }+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_attribute from: :words,+ to: :title,+ up: ->(words) { words.reverse!.join(" ") },+ down: ->(title) { title.split(" ") }+ end+ end+ .new(__FILE__),+ ]+ end++ before { input.parameters }++ it "preserves the submitted document" do+ expect(document.dig("data", "attributes", "words")).to eq(%w[Hello world])+ end+ end++ context "when existing values complete a partial merge" do+ let(:attributes) { { "width" => 800 } }+ let(:dimensions) { JsonApiKit::Name::Field.new(value: "dimensions", type: "topics") }+ let(:existing) do+ JsonApiKit::ExistingValues.for(changes, current: { dimensions => [640, 480] })+ end+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ merged_attributes from: %i[width height],+ to: :dimensions,+ up: ->(width, height) { [width, height] },+ down: ->(dimensions) { dimensions }+ end+ end+ .new(__FILE__),+ ]+ end++ it "supplies the completed value" do+ expect(input.parameters).to eq(dimensions: [800, 480])+ end++ it "keeps recovered values out of the submitted locations" do+ expect(input.locations_for(:dimensions).map(&:pointer)).to contain_exactly(+ "/data/attributes/width",+ )+ end++ context "when the existing value has an invalid converter result" do+ let(:existing) { JsonApiKit::ExistingValues.for(changes, current: { dimensions => [640] }) }++ it "preserves the existing-state failure" do+ expect { input.parameters }.to raise_error(ArgumentError, /down converter for dimensions/)+ end+ end+ end+ end++ describe "#locations_for" do+ subject(:pointers) { input.locations_for(parameter).map(&:pointer) }++ let(:attributes) { { "width" => 640, "height" => 480, "size" => [320, 240] } }+ let(:parameter) { :dimensions }+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ merged_attributes from: %i[width height],+ to: :dimensions,+ up: ->(width, height) { [width, height] },+ down: ->(dimensions) { dimensions }+ split_attribute from: :size,+ to: %i[pixel_width pixel_height],+ up: ->(size) { size },+ down: ->(width, height) { [width, height] }+ end+ end+ .new(__FILE__),+ ]+ end++ it "retains every supplied merge source" do+ expect(pointers).to contain_exactly("/data/attributes/width", "/data/attributes/height")+ end++ context "when a merge source is omitted" do+ let(:attributes) { super().except("height") }++ it "retains only the supplied location" do+ expect(pointers).to contain_exactly("/data/attributes/width")+ end+ end++ context "when an attribute is split" do+ let(:parameter) { :pixel_height }++ it "retains the original source location" do+ expect(pointers).to contain_exactly("/data/attributes/size")+ end+ end++ context "when a parameter was not supplied" do+ let(:parameter) { :title }++ it { is_expected.to be_empty }+ end++ context "when a submitted name has the wrong casing" do+ let(:attributes) { { "bad_name" => 12 } }++ it "reports a body error at the submitted location" do+ expect { pointers }.to raise_error(JsonApiKit::Request::Body::ConversionError) do |error|+ expect(error.source).to eq(pointer: "/data/attributes/bad_name")+ end+ end+ end++ context "when a submitted name belongs to a later version" do+ let(:attributes) { { "dimensions" => [640, 480] } }++ it "reports a body error at the submitted location" do+ expect { pointers }.to raise_error(JsonApiKit::Request::Body::ConversionError) do |error|+ expect(error.source).to eq(pointer: "/data/attributes/dimensions")+ end+ end+ end++ context "when the value cannot be converted" do+ let(:attributes) { { "size" => nil } }+ let(:parameter) { :pixel_height }++ it "locates the member without converting its value" do+ expect(pointers).to contain_exactly("/data/attributes/size")+ end+ end++ context "when a later change merges the split destinations" do+ let(:parameter) { :resolution }+ let(:changes) do+ super() ++ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ merged_attributes from: %i[pixel_width pixel_height],+ to: :resolution,+ up: ->(width, height) { [width, height] },+ down: ->(resolution) { resolution }+ end+ end+ .new(__FILE__),+ ]+ end++ it "retains the original location once" do+ expect(pointers).to contain_exactly("/data/attributes/size")+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/version_change/pass_through_spec.rb b/spec/lib/json_api_kit/version_change/pass_through_spec.rbindex 780735e58dd..09f5e39c9a8 100644--- a/spec/lib/json_api_kit/version_change/pass_through_spec.rb+++ b/spec/lib/json_api_kit/version_change/pass_through_spec.rb@@ -13,7 +13,7 @@ RSpec.describe JsonApiKit::VersionChange::PassThrough dodescribe "#current_pairs" doit "returns the name with its value" do- expect(pass_through.current_pairs(name => "A")).to eq([[name, "A"]])+ expect(pass_through.current_pairs({ name => "A" })).to eq([[name, "A"]])endenddiff --git a/spec/lib/json_api_kit/version_change/rename_spec.rb b/spec/lib/json_api_kit/version_change/rename_spec.rbindex 886ffb6f674..b425eaeca4c 100644--- a/spec/lib/json_api_kit/version_change/rename_spec.rb+++ b/spec/lib/json_api_kit/version_change/rename_spec.rb@@ -15,7 +15,7 @@ RSpec.describe JsonApiKit::VersionChange::Rename doenddescribe "#current_pairs" do- subject(:current_pairs) { rename.current_pairs(old_name => value) }+ subject(:current_pairs) { rename.current_pairs({ old_name => value }) }let(:value) { "2026/08/01" }diff --git a/spec/lib/json_api_kit/version_change/split_spec.rb b/spec/lib/json_api_kit/version_change/split_spec.rbindex 8301ae6b79d..11dd22cc256 100644--- a/spec/lib/json_api_kit/version_change/split_spec.rb+++ b/spec/lib/json_api_kit/version_change/split_spec.rb@@ -22,7 +22,7 @@ RSpec.describe JsonApiKit::VersionChange::Split doenddescribe "#current_pairs" do- subject(:current_pairs) { split.current_pairs(dimensions => [640, 480]) }+ subject(:current_pairs) { split.current_pairs({ dimensions => [640, 480] }) }it "pairs the converted values with the destination names" doexpect(current_pairs).to eq([[width, 640], [height, 480]])