Skip to content

A platform for community discussion. Free, open, simple.

DEV: Connect JSON:API create requests to services

Loïc Guitautf043742e4126
diff --git a/app/controllers/json_api_kit/base_controller/rendering.rb b/app/controllers/json_api_kit/base_controller/rendering.rb
index e3764faf2d1..d250b262134 100644
--- a/app/controllers/json_api_kit/base_controller/rendering.rb
+++ b/app/controllers/json_api_kit/base_controller/rendering.rb
@@ -27,10 +27,18 @@ module JsonApiKit
def set_json_format = request.format = :json
- def render_document(document)
- render json: document.to_h,
- status: document.status,
- content_type: Pagination::Profile::MEDIA_TYPE
+ def render_document(value, **options)
+ document =
+ Document.from(value) { { resource: request_resource, input: request_query, client: } }
+ options = { status: document.status, content_type: Pagination::Profile::MEDIA_TYPE }.merge(
+ options,
+ )
+ response.headers.merge!(document.headers(status: options.fetch(:status)))
+ render json: document.to_h, **options
+ end
+
+ def render_validation_errors(errors)
+ render_document(Document::Errors.new(*request_body.validation_errors(errors)))
end
def render_server_error(error)
diff --git a/app/controllers/json_api_kit/base_controller/request_input.rb b/app/controllers/json_api_kit/base_controller/request_input.rb
index a9b9830f28f..2757bc53bef 100644
--- a/app/controllers/json_api_kit/base_controller/request_input.rb
+++ b/app/controllers/json_api_kit/base_controller/request_input.rb
@@ -5,31 +5,22 @@ module JsonApiKit
module RequestInput
extend ActiveSupport::Concern
+ delegate :query, :body, to: :request_inputs, prefix: :request, private: true
+
private
- def request_body
- @request_body ||=
- begin
- verify_input(request_query)
- verify_input(Request::Body.parse(request.raw_post, resource: request_resource))
- end
- end
+ def service_params = { params: request_body.parameters, guardian: }
- def request_query
- @request_query ||=
- Request::Input::Individual.new(
- request.query_parameters,
+ def request_inputs
+ @request_inputs ||=
+ Request::Inputs.new(
+ query: request.query_parameters,
+ body: request.raw_post,
resource: request_resource,
- edition:,
)
end
def request_resource = @request_resource ||= resource.new(guardian:, edition:)
-
- def verify_input(input)
- raise Request::Invalid.new(input.refusals) if input.invalid?
- input
- end
end
end
end
diff --git a/lib/json_api_kit/document.rb b/lib/json_api_kit/document.rb
index d28794184ae..e0c7d6c1e36 100644
--- a/lib/json_api_kit/document.rb
+++ b/lib/json_api_kit/document.rb
@@ -3,8 +3,26 @@
module JsonApiKit
class Document
class << self
+ def from(value)
+ case value
+ when Document, Errors
+ value
+ when Array, ActiveRecord::Relation
+ Collection.from(value, **yield)
+ else
+ Individual.from(value, **yield)
+ end
+ end
+
private
+ def from_records(records, resource:, input:, client:)
+ request = Request.new(input.to_h, guardian: client.guardian, edition: client.edition)
+ assemble(
+ new(Query::Result.new(resource, request, records:), client:, fieldsets: input.fieldsets),
+ )
+ end
+
def build(raw, resource:, client:)
resource = resource.new(guardian: client.guardian, edition: client.edition)
input = input_class.new(raw, resource:, edition: client.edition)
@@ -29,6 +47,8 @@ module JsonApiKit
def status = "200"
+ def headers(**) = {}
+
private
attr_reader :query, :client, :fieldsets
diff --git a/lib/json_api_kit/document/collection.rb b/lib/json_api_kit/document/collection.rb
index 0833c3c4076..ff3c9c0bf48 100644
--- a/lib/json_api_kit/document/collection.rb
+++ b/lib/json_api_kit/document/collection.rb
@@ -11,6 +11,8 @@ module JsonApiKit
instance.all(params, scoped_to:)
end
end
+
+ def from(...) = from_records(...)
end
private
diff --git a/lib/json_api_kit/document/errors.rb b/lib/json_api_kit/document/errors.rb
index e1abf84b378..1de3589bc06 100644
--- a/lib/json_api_kit/document/errors.rb
+++ b/lib/json_api_kit/document/errors.rb
@@ -9,6 +9,8 @@ module JsonApiKit
def status = errors.first.status
+ def headers(**) = {}
+
def to_h = { errors: errors.map { ErrorObject.new(it).to_h } }
private
diff --git a/lib/json_api_kit/document/individual.rb b/lib/json_api_kit/document/individual.rb
index a86859fb842..c0aba2f1667 100644
--- a/lib/json_api_kit/document/individual.rb
+++ b/lib/json_api_kit/document/individual.rb
@@ -9,6 +9,13 @@ module JsonApiKit
def for(id, parameters, resource:, client:)
build(parameters, resource:, client:) { |params, instance| instance.find(id, params) }
end
+
+ def from(record, **context) = from_records([record], **context)
+ end
+
+ def headers(status: self.status)
+ return {} unless Rack::Utils.status_code(status) == 201
+ { "Location" => urls.for(query.record).to_s }
end
private
diff --git a/lib/json_api_kit/query/result.rb b/lib/json_api_kit/query/result.rb
new file mode 100644
index 00000000000..501b0288e98
--- /dev/null
+++ b/lib/json_api_kit/query/result.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Query
+ class Result < Query
+ Row = Data.define(:record)
+
+ def initialize(resource, request, records:)
+ super(resource, request)
+ @rows = records.map { Row.new(it) }
+ end
+
+ attr_reader :rows
+
+ def record = records.sole
+
+ def pages = {}
+
+ def item_cursors? = false
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body.rb b/lib/json_api_kit/request/body.rb
index f6dbb3d327b..e1f28e858d8 100644
--- a/lib/json_api_kit/request/body.rb
+++ b/lib/json_api_kit/request/body.rb
@@ -27,6 +27,10 @@ module JsonApiKit
def refusals = contract.errors.map { Error.new(it, document:) }
+ def validation_errors(errors)
+ errors.map { ValidationError.new(it, location: attributes.location_for(it.attribute)) }
+ end
+
private
attr_reader :document, :resource
diff --git a/lib/json_api_kit/request/body/attributes.rb b/lib/json_api_kit/request/body/attributes.rb
index 452331ded7d..512fbf183b3 100644
--- a/lib/json_api_kit/request/body/attributes.rb
+++ b/lib/json_api_kit/request/body/attributes.rb
@@ -33,6 +33,13 @@ module JsonApiKit
raise ConversionError.new(error, location: error_location([error.raw]))
end
+ def location_for(parameter)
+ return Location.new(document, %w[data]) if parameter == :base
+ locations_for(parameter.to_s.split(/[.\[]/, 2).first).sole
+ rescue Enumerable::SoleItemExpectedError
+ Location.new(document, %w[data attributes])
+ end
+
private
attr_reader :document, :glossary, :existing
diff --git a/lib/json_api_kit/request/body/validation_error.rb b/lib/json_api_kit/request/body/validation_error.rb
new file mode 100644
index 00000000000..50e157d3cc3
--- /dev/null
+++ b/lib/json_api_kit/request/body/validation_error.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class ValidationError < JsonApiKit::Error
+ delegate :pointer, to: :location, private: true
+
+ def initialize(error, location:)
+ @location = location.nearest_existing
+ super(error.message)
+ end
+
+ def status = "422"
+
+ def title = "Invalid input"
+
+ def source = { pointer: }
+
+ private
+
+ attr_reader :location
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/inputs.rb b/lib/json_api_kit/request/inputs.rb
new file mode 100644
index 00000000000..f6c8cafd7a3
--- /dev/null
+++ b/lib/json_api_kit/request/inputs.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Inputs
+ def initialize(query:, body:, resource:)
+ @resource = resource
+ @raw_body = body
+ @query = verify(Input::Individual.new(query, resource:, edition: resource.edition))
+ end
+
+ attr_reader :query
+
+ def body = @body ||= verify(Body.parse(raw_body, resource:))
+
+ private
+
+ attr_reader :resource, :raw_body
+
+ def verify(input)
+ raise Invalid.new(input.refusals) if input.invalid?
+ input
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/post_service_spec.rb b/spec/integration/json_api_kit/post_service_spec.rb
new file mode 100644
index 00000000000..6319ce7cf65
--- /dev/null
+++ b/spec/integration/json_api_kit/post_service_spec.rb
@@ -0,0 +1,313 @@
+# frozen_string_literal: true
+
+module JsonApiKitPostSpec
+ class UserResource < JsonApiKit::Resource
+ model User
+ type :users
+
+ attribute :username
+ attribute :email, readable: ->(guardian) { guardian.can_see_emails? }
+ end
+
+ class GroupResource < JsonApiKit::Resource
+ model Group
+ type :groups
+
+ scope { Group.none }
+
+ attribute :name, :string, writable: true
+ attribute :public_admission, :boolean, writable: true
+ attribute :full_name, :string, writable: true
+ attribute :flair_icon
+
+ has_many :users, resource: UserResource
+ end
+
+ class CreateGroup
+ include Service::Base
+
+ params(from_resource: GroupResource, only: %i[name public_admission]) do
+ attribute :bio_raw, :string
+
+ validates :name, presence: true
+ end
+
+ policy :can_create_group
+ model :group, :create_group
+
+ private
+
+ def can_create_group(guardian:)
+ guardian.is_admin?
+ end
+
+ def create_group(params:, guardian:)
+ Group.create(**params, users: [guardian.user])
+ end
+ end
+
+ class GroupsController < JsonApiKit::BaseController
+ resource GroupResource
+
+ def create
+ CreateGroup.call(service_params) do
+ on_success { |group:| render_document(group, status: :created) }
+ on_failed_contract { |contract| render_validation_errors(contract.errors) }
+ on_failed_policy(:can_create_group) { raise Discourse::InvalidAccess }
+ on_model_errors(:group) { |group| render_validation_errors(group.errors) }
+ end
+ end
+ end
+
+ class RenameGroups < JsonApiKit::VersionChange
+ version "2026-09-01"
+ description "Teams become groups with names."
+
+ renamed_type from: :teams, to: :groups
+
+ resource :groups do
+ renamed_attribute from: :label,
+ to: :name,
+ up: ->(label) { label&.strip },
+ down: ->(name) { name }
+ merged_attributes from: %i[intro details],
+ to: :bio_raw,
+ up: ->(intro, details) { [intro, details].join("\n") },
+ down: ->(biography) { biography.split("\n", 2) }
+ end
+ end
+end
+
+RSpec.describe JsonApiKitPostSpec::GroupsController, type: :request do
+ describe "#create" do
+ subject(:create_group) do
+ post path,
+ params: document.to_json,
+ headers: {
+ "HTTP_API_VERSION" => version,
+ "CONTENT_TYPE" => JsonApiKit::MediaType::JSON_API,
+ }
+ end
+
+ fab!(:admin)
+
+ let(:actor) { admin }
+ let(:path) { "/api/groups" }
+ let(:version) { "2026-09-01" }
+ let(:type) { "groups" }
+ let(:document) { { "data" => primary } }
+ let(:primary) { { "type" => type, "attributes" => attributes } }
+ let(:attributes) { { "name" => "api_group", "publicAdmission" => "false" } }
+ let(:version_changes) do
+ JsonApiKit::VersionChanges.new([JsonApiKitPostSpec::RenameGroups.new(__FILE__)])
+ end
+ let(:parsed_body) { JSON.parse(response.body) }
+ let(:group) { Group.find_by!(name: "api_group") }
+ let(:expected_attributes) do
+ { "name" => "api_group", "publicAdmission" => false, "fullName" => nil, "flairIcon" => nil }
+ end
+ let(:location) { "http://test.localhost/api/groups/#{group.id}" }
+ let(:pointer) { "/data/attributes/name" }
+
+ before do
+ freeze_time(Date.new(2026, 9, 2))
+ allow(JsonApiKit::VersionChanges).to receive(:core).and_return(version_changes)
+ sign_in(actor)
+ Rails.application.routes.disable_clear_and_finalize = true
+ Rails.application.routes.draw { post "/api/groups" => "json_api_kit_post_spec/groups#create" }
+ Rails.application.routes.disable_clear_and_finalize = false
+ end
+
+ after { Rails.application.reload_routes! }
+
+ shared_examples "a created group" do
+ it "creates the group from the submitted attributes", :aggregate_failures do
+ expect { create_group }.to change(Group, :count).by(1)
+ expect(group).to have_attributes(name: "api_group", public_admission: false)
+ end
+
+ it "returns the created representation", :aggregate_failures do
+ create_group
+
+ expect(response).to have_http_status(:created)
+ expect(JsonApiKit::MediaType.new(response.media_type)).to be_json_api
+ expect(response.headers["Location"]).to eq(location)
+ expect(parsed_body.fetch("data")).to include(
+ "type" => type,
+ "id" => group.id.to_s,
+ "attributes" => expected_attributes,
+ "links" => {
+ "self" => location,
+ },
+ )
+ end
+ end
+
+ shared_examples "a contract refusal" do
+ it "reports the submitted location without creating a group", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("status" => "422", "source" => { "pointer" => pointer }),
+ )
+ end
+ end
+
+ it_behaves_like "a created group"
+
+ context "when the client uses an older version" do
+ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE.to_s }
+ let(:type) { "teams" }
+ let(:attributes) { super().except("name").merge("label" => " api_group ") }
+ let(:expected_attributes) { super().except("name").merge("label" => "api_group") }
+
+ it_behaves_like "a created group"
+
+ context "when the converted name is invalid" do
+ let(:attributes) { super().merge("label" => " ") }
+ let(:pointer) { "/data/attributes/label" }
+
+ it_behaves_like "a contract refusal"
+ end
+
+ context "when the model rejects a merged value" do
+ let(:attributes) { super().merge("intro" => "A" * 1500, "details" => "B" * 1500) }
+
+ it "reports the submitted attributes object", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("status" => "422", "source" => { "pointer" => "/data/attributes" }),
+ )
+ end
+ end
+ end
+
+ context "when the contract declares an attribute absent from the resource" do
+ let(:attributes) { super().merge("bioRaw" => "Created through the API") }
+
+ it "supplies the attribute to the service" do
+ expect { create_group }.to change { Group.find_by(name: "api_group")&.bio_raw }.to(
+ attributes.fetch("bioRaw"),
+ )
+ end
+ end
+
+ context "when the contract omits submitted attributes" do
+ let(:attributes) do
+ super().merge("fullName" => "Ignored name", "flairIcon" => "star", "unknownField" => true)
+ end
+
+ it "ignores attributes outside the contract", :aggregate_failures do
+ create_group
+
+ expect(response).to have_http_status(:created)
+ expect(group).to have_attributes(full_name: nil, flair_icon: nil)
+ end
+ end
+
+ context "when the query selects response fields" do
+ let(:path) { "#{super()}?fields[groups]=name" }
+ let(:attributes) { super().merge("publicAdmission" => "true") }
+
+ it "applies the fieldset to the response", :aggregate_failures do
+ create_group
+
+ expect(response).to have_http_status(:created)
+ expect(group).to be_public_admission
+ expect(parsed_body.dig("data", "attributes")).to eq("name" => "api_group")
+ end
+ end
+
+ context "when the query includes related users" do
+ let(:path) { "#{super()}?include=users" }
+
+ it "renders the created group's users", :aggregate_failures do
+ create_group
+
+ expect(response).to have_http_status(:created)
+ expect(parsed_body.fetch("included")).to contain_exactly(
+ a_hash_including(
+ "type" => "users",
+ "id" => actor.id.to_s,
+ "attributes" => {
+ "username" => actor.username,
+ "email" => actor.email,
+ },
+ ),
+ )
+ expect(parsed_body.dig("data", "relationships", "users", "data")).to contain_exactly(
+ "type" => "users",
+ "id" => actor.id.to_s,
+ )
+ end
+ end
+
+ context "when the model rejects the name" do
+ let(:attributes) { super().merge("name" => "invalid group name") }
+
+ it "reports the submitted attribute", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("status" => "422", "source" => { "pointer" => pointer }),
+ )
+ end
+ end
+
+ context "when the name is null" do
+ let(:attributes) { super().merge("name" => nil) }
+
+ it_behaves_like "a contract refusal"
+ end
+
+ context "when the name is omitted" do
+ let(:attributes) { super().except("name") }
+ let(:pointer) { "/data/attributes" }
+
+ it_behaves_like "a contract refusal"
+ end
+
+ context "when attributes are omitted" do
+ let(:primary) { super().except("attributes") }
+ let(:pointer) { "/data" }
+
+ it_behaves_like "a contract refusal"
+ end
+
+ context "when the attributes object is malformed" do
+ let(:attributes) { [] }
+
+ it "refuses the document before creating a group", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("source" => { "pointer" => "/data/attributes" }),
+ )
+ end
+ end
+
+ context "when the query supplies an unsupported parameter" do
+ let(:path) { "#{super()}?sort=name" }
+
+ it "refuses the query before creating a group", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("source" => { "parameter" => "sort" }),
+ )
+ end
+ end
+
+ context "when the actor cannot create groups" do
+ fab!(:user)
+
+ let(:actor) { user }
+
+ it "preserves the service policy", :aggregate_failures do
+ expect { create_group }.not_to change(Group, :count)
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/rendering_spec.rb b/spec/integration/json_api_kit/rendering_spec.rb
new file mode 100644
index 00000000000..c9c3093b81c
--- /dev/null
+++ b/spec/integration/json_api_kit/rendering_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+module JsonApiKitRenderSpec
+ class UserResource < JsonApiKit::Resource
+ model User
+ type :users
+
+ attribute :username
+ end
+
+ class GroupResource < JsonApiKit::Resource
+ model Group
+ type :groups
+
+ scope { Group.none }
+
+ attribute :name
+ attribute :public_admission
+
+ has_many :users, resource: UserResource
+ end
+
+ class GroupsController < JsonApiKit::BaseController
+ resource GroupResource
+
+ def index = render_document(records)
+
+ def created = render_document(records.to_a, status: :created)
+
+ private
+
+ def records
+ Group.where(name: %w[render_middle render_zeta]).order(name: :desc)
+ end
+ end
+
+ class ErrorsController < JsonApiKit::BaseController
+ def index
+ render_document(JsonApiKit::Document::Errors.new(JsonApiKit::BadRequest.new("Invalid input")))
+ end
+ end
+end
+
+RSpec.describe "Rendering supplied JSON:API documents", type: :request do
+ subject(:render_collection) do
+ get path, params: query, headers: { "HTTP_API_VERSION" => JsonApiKit::Timeline.current.to_s }
+ end
+
+ fab!(:member, :user)
+ fab!(:second_group) { Fabricate(:group, name: "render_middle") }
+ fab!(:last_group) { Fabricate(:group, name: "render_zeta", users: [member]) }
+
+ let(:path) { "/api/rendered-groups" }
+ let(:query) { {} }
+ let(:parsed_body) { JSON.parse(response.body) }
+ let(:rendered_ids) { parsed_body.fetch("data").map { it.fetch("id") } }
+
+ before do
+ Rails.application.routes.disable_clear_and_finalize = true
+ Rails.application.routes.draw do
+ get "/api/rendered-groups" => "json_api_kit_render_spec/groups#index"
+ get "/api/rendered-groups/created" => "json_api_kit_render_spec/groups#created"
+ get "/api/rendered-errors" => "json_api_kit_render_spec/errors#index"
+ end
+ Rails.application.routes.disable_clear_and_finalize = false
+ end
+
+ after { Rails.application.reload_routes! }
+
+ context "when the query selects fields and included resources" do
+ let(:query) { { fields: { groups: "name,users" }, include: "users" } }
+
+ it "applies the requested representation", :aggregate_failures do
+ render_collection
+
+ expect(response).to have_http_status(:ok)
+ expect(parsed_body.fetch("data").map { it.fetch("attributes") }).to eq(
+ [{ "name" => last_group.name }, { "name" => second_group.name }],
+ )
+ expect(parsed_body.fetch("included")).to contain_exactly(
+ a_hash_including(
+ "type" => "users",
+ "id" => member.id.to_s,
+ "attributes" => {
+ "username" => member.username,
+ },
+ ),
+ )
+ end
+ end
+
+ context "when the action supplies a created collection" do
+ let(:path) { "#{super()}/created" }
+
+ it "renders the collection without an individual location", :aggregate_failures do
+ render_collection
+
+ expect(response).to have_http_status(:created)
+ expect(rendered_ids).to eq([last_group.id.to_s, second_group.id.to_s])
+ expect(response.headers).not_to have_key("Location")
+ end
+ end
+
+ context "when the action supplies an error document without a resource" do
+ let(:path) { "/api/rendered-errors" }
+ let(:query) { { unsupported: "value" } }
+
+ it "renders the prepared errors", :aggregate_failures do
+ render_collection
+
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ "status" => "400",
+ "title" => "Bad request",
+ "detail" => "Invalid input",
+ )
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document_spec.rb b/spec/lib/json_api_kit/document_spec.rb
index 78ed8bda7cc..1fa4292c655 100644
--- a/spec/lib/json_api_kit/document_spec.rb
+++ b/spec/lib/json_api_kit/document_spec.rb
@@ -25,6 +25,79 @@ RSpec.describe JsonApiKit::Document do
let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }
let(:parameters) { {} }
+ describe ".from" do
+ subject(:document) { described_class.from(value) { { resource: instance, input:, client: } } }
+
+ let(:resource) { Class.new(super()) { scope { Topic.none } } }
+ let(:instance) { resource.new(guardian:, edition:) }
+ let(:input) do
+ JsonApiKit::Request::Input::Individual.new(parameters, resource: instance, edition:)
+ end
+ let(:rendered_ids) { document.to_h[:data].map { it[:id] } }
+
+ context "when the input is a record" do
+ let(:value) { topic }
+
+ it "renders an individual resource" do
+ expect(document.to_h[:data]).to include(id: topic.id.to_s)
+ end
+ end
+
+ context "when the input is an array" do
+ let(:value) { [other_topic, topic] }
+
+ it "preserves the supplied order" do
+ expect(rendered_ids).to eq([other_topic.id.to_s, topic.id.to_s])
+ end
+ end
+
+ context "when the array contains one record" do
+ let(:value) { [topic] }
+
+ it "preserves the collection representation" do
+ expect(rendered_ids).to eq([topic.id.to_s])
+ end
+ end
+
+ context "when the array is empty" do
+ let(:value) { [] }
+
+ it "renders an empty collection" do
+ expect(document.to_h[:data]).to eq([])
+ end
+ end
+
+ context "when the input is a relation" do
+ fab!(:excluded_topic) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+
+ let(:value) { Topic.where(id: [topic.id, other_topic.id]).order(created_at: :desc) }
+
+ it "preserves its selection and order" do
+ expect(rendered_ids).to eq([other_topic.id.to_s, topic.id.to_s])
+ end
+ end
+
+ context "when the input is an existing document" do
+ subject(:document) { described_class.from(value) { raise "Unexpected request context" } }
+
+ let(:value) { JsonApiKit::Document::Collection.for(parameters, resource:, client:) }
+
+ it "returns the document without evaluating the context" do
+ expect(document).to equal(value)
+ end
+
+ context "when the document contains errors" do
+ let(:value) do
+ JsonApiKit::Document::Errors.new(JsonApiKit::BadRequest.new("Invalid input"))
+ end
+
+ it "returns the errors without evaluating the context" do
+ expect(document).to equal(value)
+ end
+ end
+ end
+ end
+
describe "Collection.for" do
subject(:document) do
JsonApiKit::Document::Collection.for(parameters, resource:, client:, scoped_to:)
diff --git a/spec/lib/json_api_kit/request/body_spec.rb b/spec/lib/json_api_kit/request/body_spec.rb
index 187260dfb6e..f59f5ae23e8 100644
--- a/spec/lib/json_api_kit/request/body_spec.rb
+++ b/spec/lib/json_api_kit/request/body_spec.rb
@@ -40,6 +40,44 @@ RSpec.describe JsonApiKit::Request::Body do
end
end
+ describe "#validation_errors" do
+ subject(:validation_errors) { body.validation_errors(errors) }
+
+ let(:document) do
+ {
+ "data" => {
+ "type" => "topics",
+ "attributes" => {
+ "displaySettings" => {
+ "theme" => "",
+ },
+ },
+ },
+ }
+ end
+ let(:errors) { Service::ContractBase.new.errors }
+
+ before { errors.add(attribute, "is invalid") }
+
+ context "when the error applies to the whole contract" do
+ let(:attribute) { :base }
+
+ it "points to the submitted resource object" do
+ expect(validation_errors.map(&:source)).to contain_exactly(pointer: "/data")
+ end
+ end
+
+ context "when the error applies to a nested attribute" do
+ let(:attribute) { :"display_settings.theme" }
+
+ it "points to the original top-level attribute" do
+ expect(validation_errors.map(&:source)).to contain_exactly(
+ pointer: "/data/attributes/displaySettings",
+ )
+ end
+ end
+ end
+
describe "#invalid?" do
context "when the type is an empty array" do
let(:document) { { "data" => { "type" => [] } } }
diff --git a/spec/lib/json_api_kit/request/inputs_spec.rb b/spec/lib/json_api_kit/request/inputs_spec.rb
new file mode 100644
index 00000000000..83e10c6f7a5
--- /dev/null
+++ b/spec/lib/json_api_kit/request/inputs_spec.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Inputs do
+ subject(:inputs) { described_class.new(query: parameters, body: json, resource:) }
+
+ let(:parameters) { { "fields" => { "topics" => "title" } } }
+ let(:document) { { "data" => { "type" => "topics", "attributes" => { "title" => "A topic" } } } }
+ let(:json) { document.to_json }
+ let(:resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ end
+ .new(guardian: Guardian.new)
+ end
+
+ describe ".new" do
+ context "when the query and body are invalid" do
+ let(:parameters) { { "unsupported" => true } }
+ let(:json) { "{" }
+
+ it "rejects the query before parsing the body" do
+ expect { inputs }.to raise_error(JsonApiKit::Request::Invalid, /unsupported/)
+ end
+ end
+ end
+
+ describe "#query" do
+ subject(:query) { inputs.query }
+
+ context "when the body is not valid JSON" do
+ let(:json) { "{" }
+
+ it "supplies the query without parsing the body" do
+ expect(query.to_h[:fields]).to eq("topics" => ["title"])
+ end
+ end
+ end
+
+ describe "#body" do
+ subject(:body) { inputs.body }
+
+ it "supplies the validated document" do
+ expect(body.to_h).to eq(document)
+ end
+
+ context "when the body is not valid JSON" do
+ let(:json) { "{" }
+
+ it "rejects the body when requested" do
+ expect { body }.to raise_error(JsonApiKit::Request::Body::Unreadable)
+ end
+ end
+
+ context "when the document has an invalid structure" do
+ let(:document) { super().merge("data" => []) }
+
+ it "rejects the document" do
+ expect { body }.to raise_error(JsonApiKit::Request::Invalid, /data must be an object/)
+ end
+ end
+ end
+end