Skip to content

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

DEV: JSON:API Kit core framework (#42306)

Loïc Guitaut9611f9a6fc85
diff --git a/lib/json_api_kit/anchoring.rb b/lib/json_api_kit/anchoring.rb
new file mode 100644
index 00000000000..47be39f88bd
--- /dev/null
+++ b/lib/json_api_kit/anchoring.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Anchoring
+ class << self
+ def for(anchor)
+ name, value = Array(anchor).first
+ name && new(name.to_s, value)
+ end
+ end
+
+ attr_reader :name, :value
+
+ def initialize(name, value)
+ @name = name
+ @value = value
+ end
+
+ def computed? = value.nil?
+ end
+end
diff --git a/lib/json_api_kit/association.rb b/lib/json_api_kit/association.rb
new file mode 100644
index 00000000000..2a44a7721c4
--- /dev/null
+++ b/lib/json_api_kit/association.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Association
+ def initialize(scope:, owner_records:, owner_key:, related_key:)
+ @scope = scope
+ @owner_records = owner_records
+ @owner_key = owner_key.to_sym
+ @related_key = related_key.to_sym
+ end
+
+ def related_scope = scope.where(related_key => owner_values)
+
+ def to_scoping = Scoping::PerOwner.new(related_scope, owner_key: related_key)
+
+ def pair(related_records)
+ related_by_key = related_records.group_by { related_value(it) }
+ positions = related_by_key.keys.each_with_index.to_h
+ related_keys.transform_values do |keys|
+ keys.sort_by { positions.fetch(it, 0) }.flat_map { related_by_key.fetch(it, []) }
+ end
+ end
+
+ private
+
+ attr_reader :scope, :owner_records, :owner_key, :related_key
+
+ def related_keys = owner_records.to_h { [it, [owner_value(it)]] }
+
+ def owner_values = owner_records.filter_map { owner_value(it) }.uniq
+
+ def owner_value(record) = record.public_send(owner_key)
+
+ def related_value(record) = record.public_send(related_key)
+ end
+end
diff --git a/lib/json_api_kit/association/through.rb b/lib/json_api_kit/association/through.rb
new file mode 100644
index 00000000000..0bffdf8fb94
--- /dev/null
+++ b/lib/json_api_kit/association/through.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Association
+ class Through < Association
+ def initialize(join_scope:, join_owner_key:, join_related_key:, **)
+ super(**)
+ @join_scope = join_scope
+ @join_owner_key = join_owner_key.to_sym
+ @join_related_key = join_related_key.to_sym
+ end
+
+ def related_scope = scope.where(related_key => joins.select(join_related_key))
+
+ private
+
+ attr_reader :join_scope, :join_owner_key, :join_related_key
+
+ def joins = join_scope.where(join_owner_key => owner_values)
+
+ def related_keys
+ pairs = joins.pluck(join_owner_key, join_related_key).group_by(&:first)
+ owner_records.to_h { [it, pairs.fetch(owner_value(it), []).map(&:last)] }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/bad_request.rb b/lib/json_api_kit/bad_request.rb
new file mode 100644
index 00000000000..88cde8bccc3
--- /dev/null
+++ b/lib/json_api_kit/bad_request.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class BadRequest < Error
+ def status = "400"
+ end
+end
diff --git a/lib/json_api_kit/columns.rb b/lib/json_api_kit/columns.rb
new file mode 100644
index 00000000000..4559a72bc0d
--- /dev/null
+++ b/lib/json_api_kit/columns.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Columns
+ class << self
+ def all = All.new
+
+ def for(names)
+ return all if names.include?(nil)
+ new(names)
+ end
+ end
+
+ def initialize(names)
+ @names = names.uniq
+ end
+
+ def apply(scope) = scope.select(*names)
+
+ def with(*more) = Columns.for(names + more)
+
+ def ==(other) = other.instance_of?(self.class) && other.names == names
+
+ alias eql? ==
+
+ def hash = [self.class, names].hash
+
+ protected
+
+ attr_reader :names
+ end
+end
diff --git a/lib/json_api_kit/columns/all.rb b/lib/json_api_kit/columns/all.rb
new file mode 100644
index 00000000000..a526d1bba71
--- /dev/null
+++ b/lib/json_api_kit/columns/all.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Columns
+ class All < Columns
+ def initialize = super([])
+
+ def apply(scope) = scope
+
+ def with(*) = self
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor.rb b/lib/json_api_kit/declarations/anchor.rb
new file mode 100644
index 00000000000..b542806ed53
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchor.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchor
+ class NoRow < BadRequest
+ def initialize(name, value)
+ @name = name
+ super("No record has #{name} #{value.inspect}.")
+ end
+
+ def title = "No row for the anchor"
+
+ def source = { parameter: "page[anchor][#{name}]" }
+
+ private
+
+ attr_reader :name
+ end
+
+ IDENTITY = "id"
+
+ attr_reader :name
+
+ def initialize(name, &condition)
+ @name = name.to_s
+ @condition = condition
+ end
+
+ def locatable_in?(order) = computed? || order.leading.named?(name) || identity?
+
+ def locate(scope, value:, order:, guardian:)
+ kind_for(order.leading, value, guardian).locate(scope, order:)
+ end
+
+ private
+
+ attr_reader :condition
+
+ def kind_for(key, value, guardian)
+ return Computed.new(condition, guardian) if computed?
+ return Value.new(key, value) if key.named?(name)
+ return Identity.new(name, value) if identity?
+ raise ArgumentError, "The anchor is #{name}, but this request sorts by #{key}."
+ end
+
+ def computed? = condition.present?
+
+ def identity? = name == IDENTITY
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor/computed.rb b/lib/json_api_kit/declarations/anchor/computed.rb
new file mode 100644
index 00000000000..1d2d9b51e5f
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchor/computed.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchor
+ class Computed
+ def initialize(condition, guardian)
+ @condition = condition
+ @guardian = guardian
+ end
+
+ def locate(scope, order:) = order.locate(condition.call(scope, guardian))
+
+ private
+
+ attr_reader :condition, :guardian
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor/identity.rb b/lib/json_api_kit/declarations/anchor/identity.rb
new file mode 100644
index 00000000000..4dae9ddff4d
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchor/identity.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchor
+ class Identity
+ def initialize(name, value)
+ @name = name
+ @value = value
+ end
+
+ def locate(scope, order:)
+ order.locate(scope.where(scope.primary_key => value)) or raise NoRow.new(name, value)
+ end
+
+ private
+
+ attr_reader :name, :value
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor/value.rb b/lib/json_api_kit/declarations/anchor/value.rb
new file mode 100644
index 00000000000..394634d09f0
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchor/value.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchor
+ class Value
+ def initialize(key, value)
+ @key = key
+ @value = value
+ end
+
+ def locate(scope, order:)
+ order.enter(scope, at_or_after: key.at_or_after(scope, value))
+ end
+
+ private
+
+ attr_reader :key, :value
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchors.rb b/lib/json_api_kit/declarations/anchors.rb
new file mode 100644
index 00000000000..e7f5c3d14c7
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchors.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchors
+ delegate :fetch, to: :anchors
+
+ def initialize(anchors, guardian:)
+ @anchors = anchors.index_by(&:name)
+ @guardian = guardian
+ end
+
+ def locate(anchoring, scope:, order:)
+ fetch(anchoring.name).locate(scope, value: anchoring.value, order:, guardian:)
+ end
+
+ private
+
+ attr_reader :anchors, :guardian
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/attribute.rb b/lib/json_api_kit/declarations/attribute.rb
new file mode 100644
index 00000000000..08fdc7ccc18
--- /dev/null
+++ b/lib/json_api_kit/declarations/attribute.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Attribute
+ attr_reader :name
+
+ def initialize(name, &value)
+ @name = name.to_s
+ @value = value
+ end
+
+ def value_for(record)
+ return value.call(record) if value
+ record.public_send(name)
+ end
+
+ def column_for(schema)
+ return if value
+ schema.column(name)
+ end
+
+ private
+
+ attr_reader :value
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/attributes.rb b/lib/json_api_kit/declarations/attributes.rb
new file mode 100644
index 00000000000..152ebf6378e
--- /dev/null
+++ b/lib/json_api_kit/declarations/attributes.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Attributes
+ def initialize(attributes, schema:)
+ @attributes = attributes
+ @schema = schema
+ end
+
+ def values_for(record) = attributes.to_h { [it.name, it.value_for(record)] }
+
+ def columns = Columns.for(attributes.map { it.column_for(schema) })
+
+ private
+
+ attr_reader :attributes, :schema
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/fields.rb b/lib/json_api_kit/declarations/fields.rb
new file mode 100644
index 00000000000..3a1dff2722a
--- /dev/null
+++ b/lib/json_api_kit/declarations/fields.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Fields
+ Collision = Class.new(StandardError)
+
+ RESERVED = %w[type id].freeze
+
+ def self.for(names, **declarations)
+ return All.new(**declarations) unless names
+ new(names, **declarations)
+ end
+
+ def initialize(names, attributes:, relationships:, schema:)
+ @names = names
+ @declared_attributes = attributes
+ @declared_relationships = relationships
+ @schema = schema
+ verify_field_names
+ end
+
+ def attributes = @attributes ||= Attributes.new(pick(declared_attributes), schema:)
+
+ def relationships = Relationships.new(pick(declared_relationships))
+
+ def columns = attributes.columns
+
+ private
+
+ attr_reader :names, :declared_attributes, :declared_relationships, :schema
+
+ def pick(fields) = fields.select { names.include?(it.name) }
+
+ def all_fields = declared_attributes + declared_relationships
+
+ def declared_names = all_fields.map(&:name)
+
+ def verify_field_names
+ refuse_reserved_names
+ refuse_repeated_names
+ end
+
+ def refuse_reserved_names
+ reserved_names = declared_names & RESERVED
+ return if reserved_names.empty?
+ raise Collision, "#{reserved_names.join(", ")} says which record this is, not what it holds"
+ end
+
+ def refuse_repeated_names
+ repeated_names = declared_names.tally.filter_map { |name, count| name if count > 1 }
+ return if repeated_names.empty?
+ raise Collision, "#{repeated_names.join(", ")} names two fields"
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/fields/all.rb b/lib/json_api_kit/declarations/fields/all.rb
new file mode 100644
index 00000000000..7423deaaca9
--- /dev/null
+++ b/lib/json_api_kit/declarations/fields/all.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Fields
+ class All < Fields
+ def initialize(**declarations) = super(nil, **declarations)
+
+ def columns = Columns.all
+
+ private
+
+ def pick(fields) = fields
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/filter.rb b/lib/json_api_kit/declarations/filter.rb
new file mode 100644
index 00000000000..7cc542ab9d5
--- /dev/null
+++ b/lib/json_api_kit/declarations/filter.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Filter
+ attr_reader :name
+
+ def initialize(name, &condition)
+ @name = name.to_s
+ @condition = condition || Equality.new(@name)
+ end
+
+ def apply(scope, value) = condition.call(scope, value)
+
+ private
+
+ attr_reader :condition
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/filter/equality.rb b/lib/json_api_kit/declarations/filter/equality.rb
new file mode 100644
index 00000000000..6e1177bdece
--- /dev/null
+++ b/lib/json_api_kit/declarations/filter/equality.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Filter
+ class Equality
+ def initialize(name)
+ @name = name
+ end
+
+ def call(scope, value) = scope.where(name => value)
+
+ private
+
+ attr_reader :name
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/filters.rb b/lib/json_api_kit/declarations/filters.rb
new file mode 100644
index 00000000000..fd3780bfc41
--- /dev/null
+++ b/lib/json_api_kit/declarations/filters.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Filters
+ delegate :fetch, to: :filters
+
+ def initialize(filters)
+ @filters = filters.index_by(&:name)
+ end
+
+ def apply(scope, filtering = {})
+ return scope if filtering.blank?
+ filtering.reduce(scope) { |narrowed, (name, value)| fetch(name).apply(narrowed, value) }
+ end
+
+ private
+
+ attr_reader :filters
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/include_paths.rb b/lib/json_api_kit/declarations/include_paths.rb
new file mode 100644
index 00000000000..6562fdbc2bc
--- /dev/null
+++ b/lib/json_api_kit/declarations/include_paths.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class IncludePaths
+ Unresolved = Class.new(StandardError)
+
+ def initialize(deep_paths, relationships:)
+ @deep_paths = Paths.new(deep_paths)
+ @relationships = relationships
+ refuse_unresolved
+ end
+
+ def allow(paths)
+ refuse_unknown(paths)
+ paths
+ end
+
+ def include?(path) = path.entered? || allowed_paths.include?(path)
+
+ private
+
+ attr_reader :deep_paths, :relationships
+
+ def refuse_unknown(paths)
+ unknown_paths = paths.reject { include?(it) }
+ return if unknown_paths.empty?
+ raise KeyError, "There is no relationship path named #{unknown_paths.join(", ")}."
+ end
+
+ def allowed_paths = @allowed_paths ||= relationships.paths + deep_paths
+
+ def refuse_unresolved
+ unresolved_paths = deep_paths.reject { relationships.resolves?(it) }
+ return if unresolved_paths.empty?
+ raise Unresolved, "#{unresolved_paths.join(", ")} reads a relationship nobody declares"
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/relationship.rb b/lib/json_api_kit/declarations/relationship.rb
new file mode 100644
index 00000000000..e04fd419843
--- /dev/null
+++ b/lib/json_api_kit/declarations/relationship.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Relationship
+ attr_reader :name, :resource
+
+ def initialize(name, resource:)
+ @name = name.to_s
+ @resource = resource
+ end
+
+ def listing(params, guardian:, scoped_to:) = resource.all(params, guardian:, scoped_to:)
+
+ def resolves?(path) = resource.resolves?(path)
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/relationship/to_many.rb b/lib/json_api_kit/declarations/relationship/to_many.rb
new file mode 100644
index 00000000000..725783b43c9
--- /dev/null
+++ b/lib/json_api_kit/declarations/relationship/to_many.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Relationship
+ class ToMany < Relationship
+ def scoping(association) = association.to_scoping
+
+ def linkage(records) = Linkage::ToMany.new(records.page(resource.page_size))
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/relationship/to_one.rb b/lib/json_api_kit/declarations/relationship/to_one.rb
new file mode 100644
index 00000000000..6f6dd5be0fe
--- /dev/null
+++ b/lib/json_api_kit/declarations/relationship/to_one.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Relationship
+ class ToOne < Relationship
+ def scoping(association) = association.to_scoping
+
+ def linkage(records) = Linkage::ToOne.new(records)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/relationships.rb b/lib/json_api_kit/declarations/relationships.rb
new file mode 100644
index 00000000000..2043109891a
--- /dev/null
+++ b/lib/json_api_kit/declarations/relationships.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Relationships
+ def initialize(relationships)
+ @relationships = relationships.index_by(&:name)
+ end
+
+ def pick(names) = relationships.slice(*names).values
+
+ def names = relationships.keys
+
+ def paths = Paths.new(names)
+
+ def resolves?(path)
+ relationship = relationships[path.current]
+ return false unless relationship
+ return true if path.last?
+ relationship.resolves?(path.next)
+ end
+
+ private
+
+ attr_reader :relationships
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/sort.rb b/lib/json_api_kit/declarations/sort.rb
new file mode 100644
index 00000000000..f84d2d517c3
--- /dev/null
+++ b/lib/json_api_kit/declarations/sort.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Sort
+ SEPARATOR = "."
+
+ def self.for(name, ...)
+ return Related.new(name, ...) if name.to_s.include?(SEPARATOR)
+ new(name, ...)
+ end
+
+ attr_reader :name
+
+ def initialize(name, column: nil, sql: nil, joins: [], nulls: nil)
+ @name = name.to_s
+ @column = column
+ @sql = sql
+ @joins = joins
+ @nulls = nulls
+ end
+
+ def key(schema:, direction:)
+ Pagination::Keyset::Key.new(
+ attribute,
+ model: schema.model,
+ direction:,
+ sql: sql_for(schema),
+ joins:,
+ nulls: placement(schema),
+ )
+ end
+
+ private
+
+ attr_reader :column, :sql, :joins, :nulls
+
+ def attribute = (column || name.tr(SEPARATOR, "_")).to_sym
+
+ def sql_for(_schema) = sql
+
+ def placement(schema)
+ return nulls if nulls
+ :last if schema.nullable?(attribute)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/sort/related.rb b/lib/json_api_kit/declarations/sort/related.rb
new file mode 100644
index 00000000000..8599aba9e33
--- /dev/null
+++ b/lib/json_api_kit/declarations/sort/related.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Sort
+ class Related < Sort
+ private
+
+ def sql_for(schema) = sql || "#{schema.table_of(association)}.#{related_column}"
+
+ def joins = super.presence || association
+
+ def nulls = super || :last
+
+ def association = parts.first.to_sym
+
+ def related_column = parts.last
+
+ def parts = @parts ||= name.split(SEPARATOR)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/sorts.rb b/lib/json_api_kit/declarations/sorts.rb
new file mode 100644
index 00000000000..d6cf5c45471
--- /dev/null
+++ b/lib/json_api_kit/declarations/sorts.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Sorts
+ delegate :fetch, to: :sorts
+
+ def initialize(sorts, schema:, default: {}, unique_by: nil)
+ @sorts = sorts.index_by(&:name)
+ @schema = schema
+ @default = default.to_h.transform_keys(&:to_s)
+ @unique_by = Array(unique_by.presence || schema.primary_key)
+ end
+
+ def keyset(ordering = {}) = Pagination::Keyset.new(keys(ordering.presence || default))
+
+ private
+
+ attr_reader :sorts, :schema, :default, :unique_by
+
+ def keys(ordering)
+ [
+ *ordering.map { |name, direction| fetch(name).key(schema:, direction:) },
+ *unique_keys(leading_direction(ordering)),
+ ]
+ end
+
+ def unique_keys(direction) = unique_by.map { Sort.for(it).key(schema:, direction:) }
+
+ def leading_direction(ordering) = ordering.values.first || :asc
+ end
+ end
+end
diff --git a/lib/json_api_kit/document.rb b/lib/json_api_kit/document.rb
new file mode 100644
index 00000000000..2c8d495e06b
--- /dev/null
+++ b/lib/json_api_kit/document.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ def self.build(parameters, resource:, urls:)
+ contract_class
+ .new(
+ **parameters.to_hash.deep_dup,
+ options: {
+ resource:,
+ raw_parameters: parameters.with_indifferent_access,
+ },
+ )
+ .then do |contract|
+ next Errors.new(*Request::Contract::Mapper.new(contract.errors).to_a) if contract.invalid?
+ new(yield, urls:).tap(&:to_h)
+ end
+ rescue Error => error
+ Errors.new(error)
+ end
+ private_class_method :build
+
+ def initialize(query, urls:)
+ @query = query
+ @urls = urls
+ end
+
+ def to_h = @to_h ||= { data:, included:, links: }
+
+ def status = "200"
+
+ private
+
+ attr_reader :query, :urls
+
+ def contents = @contents ||= Contents.new(primary_records, query.included)
+
+ def links = { self: urls.current.to_s }
+
+ def included = contents.related.map { ResourceObject.new(it, urls:).to_h }
+ end
+end
diff --git a/lib/json_api_kit/document/collection.rb b/lib/json_api_kit/document/collection.rb
new file mode 100644
index 00000000000..6d70731aaf3
--- /dev/null
+++ b/lib/json_api_kit/document/collection.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class Collection < Document
+ class << self
+ def contract_class = Request::Contract::Collection
+
+ def for(parameters, resource:, guardian:, urls:, scoped_to: nil)
+ build(parameters, resource:, urls:) { resource.all(parameters, guardian:, scoped_to:) }
+ end
+ end
+
+ private
+
+ def primary_records = query.records
+
+ def data = contents.primary.map { ResourceObject.new(it, urls:, meta: page_meta(it)).to_h }
+
+ def page_meta(record)
+ return {} unless query.item_cursors?
+ { page: { cursor: record.cursor.to_s } }
+ end
+
+ def links = super.merge(PageLinks.new(urls.current, query.pages).to_h)
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/contents.rb b/lib/json_api_kit/document/contents.rb
new file mode 100644
index 00000000000..9e5591665f6
--- /dev/null
+++ b/lib/json_api_kit/document/contents.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class Contents
+ def initialize(primary_records, related_records)
+ @primary_records = primary_records
+ @related_records = related_records
+ end
+
+ def primary = @primary ||= identities.map { merged_records.fetch(it) }
+
+ def related = @related ||= merged_records.except(*identities).values
+
+ private
+
+ attr_reader :primary_records, :related_records
+
+ def identities = @identities ||= primary_records.map(&:identity)
+
+ def merged_records
+ @merged_records ||=
+ [*primary_records, *related_records].group_by(&:identity)
+ .transform_values { it.reduce(:merge) }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/error_object.rb b/lib/json_api_kit/document/error_object.rb
new file mode 100644
index 00000000000..d0b8ca1c33d
--- /dev/null
+++ b/lib/json_api_kit/document/error_object.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class ErrorObject
+ delegate :status, :title, :detail, :source, :meta, to: :error, private: true
+
+ def initialize(error)
+ @error = error
+ end
+
+ def to_h = { status:, title:, detail:, source:, links:, meta: }.compact_blank
+
+ private
+
+ attr_reader :error
+
+ def links = error.type&.then { { type: it } }
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/errors.rb b/lib/json_api_kit/document/errors.rb
new file mode 100644
index 00000000000..e1abf84b378
--- /dev/null
+++ b/lib/json_api_kit/document/errors.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class Errors
+ def initialize(*errors)
+ @errors = errors
+ end
+
+ def status = errors.first.status
+
+ def to_h = { errors: errors.map { ErrorObject.new(it).to_h } }
+
+ private
+
+ attr_reader :errors
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/individual.rb b/lib/json_api_kit/document/individual.rb
new file mode 100644
index 00000000000..82d22bf6bc5
--- /dev/null
+++ b/lib/json_api_kit/document/individual.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class Individual < Document
+ class << self
+ def contract_class = Request::Contract::Individual
+
+ def for(id, parameters, resource:, guardian:, urls:)
+ build(parameters, resource:, urls:) { resource.find(id, parameters, guardian:) }
+ end
+ end
+
+ private
+
+ def primary_records = [query.record]
+
+ def data = ResourceObject.new(contents.primary.sole, urls:).to_h
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/page_links.rb b/lib/json_api_kit/document/page_links.rb
new file mode 100644
index 00000000000..676c6e98c58
--- /dev/null
+++ b/lib/json_api_kit/document/page_links.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class PageLinks
+ def initialize(url, pages)
+ @url = url
+ @pages = pages
+ end
+
+ def to_h
+ return {} if pages.empty?
+ { prev: link(:before, pages[:before]), next: link(:after, pages[:after]) }
+ end
+
+ private
+
+ attr_reader :url, :pages
+
+ def link(end_of_the_page, cursor)
+ return unless cursor
+ url.at(end_of_the_page => cursor).to_s
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/relationship_object.rb b/lib/json_api_kit/document/relationship_object.rb
new file mode 100644
index 00000000000..32f4c70b90e
--- /dev/null
+++ b/lib/json_api_kit/document/relationship_object.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class RelationshipObject
+ delegate :pages, to: :linkage, private: true
+
+ def initialize(linkage, urls:, owner:, name:)
+ @linkage = linkage
+ @urls = urls
+ @owner = owner
+ @name = name
+ end
+
+ def to_h = { data:, links: }
+
+ private
+
+ attr_reader :linkage, :urls, :owner, :name
+
+ def data = linkage.collapse { it.identity.to_h }
+
+ def links = { self: relationship_url.to_s, related: related_url.to_s }.merge(page_links)
+
+ def relationship_url = urls.relationship(owner.type, owner.id, name)
+
+ def related_url = urls.related(owner.type, owner.id, name)
+
+ def page_links = PageLinks.new(relationship_url, pages).to_h
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/resource_object.rb b/lib/json_api_kit/document/resource_object.rb
new file mode 100644
index 00000000000..8afcc931dd1
--- /dev/null
+++ b/lib/json_api_kit/document/resource_object.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class ResourceObject
+ delegate :type, :id, :attributes, to: :record, private: true
+
+ def initialize(record, urls:, meta: {})
+ @record = record
+ @urls = urls
+ @meta = meta
+ end
+
+ def to_h = { type:, id:, attributes:, relationships:, links:, meta: }.compact_blank
+
+ private
+
+ attr_reader :record, :urls, :meta
+
+ def relationships
+ record.relationships.to_h do |name, linkage|
+ [name, RelationshipObject.new(linkage, urls:, owner: record, name:).to_h]
+ end
+ end
+
+ def links = { self: urls.record(type, id).to_s }
+ end
+ end
+end
diff --git a/lib/json_api_kit/error.rb b/lib/json_api_kit/error.rb
new file mode 100644
index 00000000000..a5c89d97544
--- /dev/null
+++ b/lib/json_api_kit/error.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Error < StandardError
+ def detail = message
+
+ def title = "Bad request"
+
+ def source = {}
+
+ def type = nil
+
+ def meta = {}
+ end
+end
diff --git a/lib/json_api_kit/included.rb b/lib/json_api_kit/included.rb
new file mode 100644
index 00000000000..092c2b87f55
--- /dev/null
+++ b/lib/json_api_kit/included.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Included
+ include Enumerable
+
+ class << self
+ def for(records) = new(related_to(records))
+
+ private
+
+ def related_to(records)
+ related_records = records.flat_map(&:related_records)
+ return related_records if related_records.empty?
+ related_records + related_to(related_records)
+ end
+ end
+
+ def initialize(records)
+ @records = records
+ end
+
+ delegate :empty?, to: :records
+
+ def each(&) = records.each(&)
+
+ private
+
+ attr_reader :records
+ end
+end
diff --git a/lib/json_api_kit/joins.rb b/lib/json_api_kit/joins.rb
new file mode 100644
index 00000000000..8c3e18acc5f
--- /dev/null
+++ b/lib/json_api_kit/joins.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Joins
+ def self.for(declarations)
+ return declarations if declarations.is_a?(self)
+ new(Array.wrap(declarations))
+ end
+
+ def initialize(declarations)
+ @declarations = declarations.uniq
+ end
+
+ def apply(scope) = scope.joins(statements).left_outer_joins(associations)
+
+ def +(other) = self.class.new(declarations + other.declarations)
+
+ def ==(other) = other.instance_of?(self.class) && other.declarations == declarations
+
+ alias eql? ==
+
+ def hash = [self.class, declarations].hash
+
+ protected
+
+ attr_reader :declarations
+
+ private
+
+ def statements = declarations.grep(String)
+
+ def associations = declarations - statements
+ end
+end
diff --git a/lib/json_api_kit/linkage.rb b/lib/json_api_kit/linkage.rb
new file mode 100644
index 00000000000..44adcb8ddca
--- /dev/null
+++ b/lib/json_api_kit/linkage.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Linkage
+ attr_reader :records
+
+ def initialize(records)
+ @records = records
+ end
+
+ def pages = {}
+ end
+end
diff --git a/lib/json_api_kit/linkage/to_many.rb b/lib/json_api_kit/linkage/to_many.rb
new file mode 100644
index 00000000000..8de2affa933
--- /dev/null
+++ b/lib/json_api_kit/linkage/to_many.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Linkage
+ class ToMany < Linkage
+ def initialize(page, previous_page: nil)
+ super(page.records)
+ @next_page = page.cursor
+ @previous_page = previous_page
+ end
+
+ def collapse(&) = records.map(&)
+
+ def pages = { before: previous, after: self.next }
+
+ def next = next_page&.to_s
+
+ def previous = previous_page&.to_s
+
+ private
+
+ attr_reader :next_page, :previous_page
+ end
+ end
+end
diff --git a/lib/json_api_kit/linkage/to_one.rb b/lib/json_api_kit/linkage/to_one.rb
new file mode 100644
index 00000000000..9163c82c747
--- /dev/null
+++ b/lib/json_api_kit/linkage/to_one.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Linkage
+ class ToOne < Linkage
+ def collapse(&) = records.first&.then(&)
+ end
+ end
+end
diff --git a/lib/json_api_kit/not_found.rb b/lib/json_api_kit/not_found.rb
new file mode 100644
index 00000000000..1a020dd50b2
--- /dev/null
+++ b/lib/json_api_kit/not_found.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class NotFound < Error
+ def initialize(detail = "No record has this ID.")
+ super
+ end
+
+ def status = "404"
+
+ def title = "No such record"
+ end
+end
diff --git a/lib/json_api_kit/page/limits.rb b/lib/json_api_kit/page/limits.rb
new file mode 100644
index 00000000000..cdf7db8a40d
--- /dev/null
+++ b/lib/json_api_kit/page/limits.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Limits
+ OutOfRange = Class.new(StandardError)
+
+ DEFAULT = 25
+ MAX = 100
+
+ attr_reader :max
+
+ def initialize(max: MAX, default: [DEFAULT, max].min)
+ @max = max
+ @default = default
+ verify_bounds
+ end
+
+ def size(page_size = nil) = page_size || default
+
+ private
+
+ attr_reader :default
+
+ def verify_bounds
+ raise OutOfRange, "A maximum page size must be 1 or more, not #{max}." if max < 1
+ return if default.between?(1, max)
+ raise OutOfRange, "A default page size must be between 1 and #{max}, not #{default}."
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/per_owner.rb b/lib/json_api_kit/page/per_owner.rb
new file mode 100644
index 00000000000..8f8335a6f35
--- /dev/null
+++ b/lib/json_api_kit/page/per_owner.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class PerOwner
+ def initialize(owner_key)
+ @owner_key = owner_key
+ end
+
+ def paginate(scope, order:, limits:, anchors: nil)
+ Pagination::PagePerOwner.new(scope, order:, size: limits.size, owner_key:)
+ end
+
+ private
+
+ attr_reader :owner_key
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/requested.rb b/lib/json_api_kit/page/requested.rb
new file mode 100644
index 00000000000..b800e45d15e
--- /dev/null
+++ b/lib/json_api_kit/page/requested.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Requested
+ def self.for(size: nil, after: nil, before: nil, anchoring: nil, **window)
+ return Around.new(anchoring, size:, **window) if anchoring
+ return After.new(after, size:) if after
+ return Before.new(before, size:) if before
+ First.new(size:)
+ end
+
+ def initialize(size: nil)
+ @size = size
+ end
+
+ private
+
+ attr_reader :size
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/requested/after.rb b/lib/json_api_kit/page/requested/after.rb
new file mode 100644
index 00000000000..31194c46b54
--- /dev/null
+++ b/lib/json_api_kit/page/requested/after.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Requested
+ class After < Requested
+ def initialize(cursor, size: nil)
+ super(size:)
+ @cursor = cursor
+ end
+
+ def paginate(scope, order:, limits:, anchors: nil)
+ Pagination::Paginator.for(scope, order:, size: limits.size(size), after: cursor)
+ end
+
+ private
+
+ attr_reader :cursor
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/requested/around.rb b/lib/json_api_kit/page/requested/around.rb
new file mode 100644
index 00000000000..fb3013837e9
--- /dev/null
+++ b/lib/json_api_kit/page/requested/around.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Requested
+ class Around < Requested
+ def initialize(
+ anchoring,
+ size: nil,
+ before_size: nil,
+ after_size: nil,
+ include_anchor: true
+ )
+ super(size:)
+ @anchoring = anchoring
+ @before_size = before_size
+ @after_size = after_size
+ @include_anchor = include_anchor
+ end
+
+ def paginate(scope, order:, limits:, anchors:)
+ row = anchors.locate(anchoring, scope:, order:)
+ return window(limits).paginate(scope, order:, row:) if row
+ return Pagination::EmptyPage.new unless anchoring.computed?
+ First.new(size:).paginate(scope, order:, limits:)
+ end
+
+ private
+
+ attr_reader :anchoring, :before_size, :after_size
+
+ def window(limits)
+ Window.new(
+ page_size: limits.size(size),
+ before: before_size,
+ after: after_size,
+ include_anchor: @include_anchor,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/requested/before.rb b/lib/json_api_kit/page/requested/before.rb
new file mode 100644
index 00000000000..4eb6a239630
--- /dev/null
+++ b/lib/json_api_kit/page/requested/before.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Requested
+ class Before < Requested
+ def initialize(cursor, size: nil)
+ super(size:)
+ @cursor = cursor
+ end
+
+ def paginate(scope, order:, limits:, anchors: nil)
+ Pagination::Paginator.for(scope, order:, size: limits.size(size), before: cursor)
+ end
+
+ private
+
+ attr_reader :cursor
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/requested/first.rb b/lib/json_api_kit/page/requested/first.rb
new file mode 100644
index 00000000000..d2974357216
--- /dev/null
+++ b/lib/json_api_kit/page/requested/first.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Requested
+ class First < Requested
+ def paginate(scope, order:, limits:, anchors: nil)
+ Pagination::Paginator.for(scope, order:, size: limits.size(size))
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/page/window.rb b/lib/json_api_kit/page/window.rb
new file mode 100644
index 00000000000..dcb00f9fb1f
--- /dev/null
+++ b/lib/json_api_kit/page/window.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Page
+ class Window
+ def initialize(page_size:, before: nil, after: nil, include_anchor: true)
+ @include_anchor = include_anchor
+ @before = before.to_i
+ @after = after || (before ? 0 : page_size - anchor_rows)
+ end
+
+ attr_reader :before, :after
+
+ def paginate(scope, order:, row:)
+ Pagination::Around.new(scope, order:, row:, before:, after:, include_row: include_anchor?)
+ end
+
+ private
+
+ def include_anchor? = @include_anchor
+
+ def anchor_rows = include_anchor? ? 1 : 0
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/around.rb b/lib/json_api_kit/pagination/around.rb
new file mode 100644
index 00000000000..acded996899
--- /dev/null
+++ b/lib/json_api_kit/pagination/around.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Around
+ def initialize(scope, order:, row:, before: 0, after: 0, include_row: true)
+ @scope = scope
+ @order = order
+ @row = row
+ @before = before
+ @after = after
+ @include_row = include_row
+ end
+
+ def rows = page_before.rows + anchor + page_after.rows
+
+ def next = page_after.next
+
+ def previous = page_before.previous
+
+ private
+
+ attr_reader :scope, :order, :row, :before, :after
+
+ def include_row? = @include_row
+
+ def anchor
+ return [] unless include_row?
+ [row]
+ end
+
+ def page_before
+ @page_before ||= Paginator::Backwards.new(scope, order:, size: before, from: row.position)
+ end
+
+ def page_after
+ @page_after ||= Paginator::Forwards.new(scope, order:, size: after, from: row.position)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/cursor.rb b/lib/json_api_kit/pagination/cursor.rb
new file mode 100644
index 00000000000..0cd7d9286b2
--- /dev/null
+++ b/lib/json_api_kit/pagination/cursor.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Cursor
+ UnsupportedValue = Class.new(ArgumentError)
+
+ TIME = ->(value) { value.acts_like?(:time) }
+ DATE = ->(value) { value.acts_like?(:date) }
+ private_constant :TIME, :DATE
+
+ class << self
+ def valid?(raw)
+ parse(raw)
+ true
+ rescue ArgumentError
+ false
+ end
+
+ def parse(raw)
+ values = JSON.parse(Base64.urlsafe_decode64(raw.to_s))
+ raise ArgumentError, "a cursor holds a list of values" unless values.is_a?(Array)
+ new(values.map { coerce(it) })
+ rescue JSON::ParserError
+ raise ArgumentError, "a cursor is JSON in base64"
+ end
+
+ def coerce(value)
+ case value
+ when TIME
+ value.getutc.iso8601(6)
+ when DATE
+ value.iso8601
+ when BigDecimal
+ value.to_s
+ when nil, true, false, String, Numeric
+ value
+ else
+ raise UnsupportedValue, "a #{value.class} cannot travel in a cursor"
+ end
+ end
+ end
+
+ attr_reader :values
+
+ def initialize(values) = @values = values
+
+ def to_s = @to_s ||= Base64.urlsafe_encode64(JSON.generate(values), padding: false)
+
+ def ==(other) = other.is_a?(self.class) && other.values == values
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/direction.rb b/lib/json_api_kit/pagination/direction.rb
new file mode 100644
index 00000000000..9bc061e13f0
--- /dev/null
+++ b/lib/json_api_kit/pagination/direction.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Direction
+ def self.for(direction)
+ case direction.to_s
+ when "asc"
+ Ascending.new
+ when "desc"
+ Descending.new
+ else
+ raise ArgumentError, "unknown direction: #{direction}"
+ end
+ end
+
+ def ==(other) = other.instance_of?(self.class)
+
+ alias eql? ==
+
+ def hash = self.class.hash
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/direction/ascending.rb b/lib/json_api_kit/pagination/direction/ascending.rb
new file mode 100644
index 00000000000..00a386638a3
--- /dev/null
+++ b/lib/json_api_kit/pagination/direction/ascending.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Direction
+ class Ascending < Direction
+ def to_sym = :asc
+
+ def to_sql = "ASC"
+
+ def operator = ">"
+
+ def other_way = :desc
+
+ def nulls_first? = false
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/direction/descending.rb b/lib/json_api_kit/pagination/direction/descending.rb
new file mode 100644
index 00000000000..1457035cd53
--- /dev/null
+++ b/lib/json_api_kit/pagination/direction/descending.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Direction
+ class Descending < Direction
+ def to_sym = :desc
+
+ def to_sql = "DESC"
+
+ def operator = "<"
+
+ def other_way = :asc
+
+ def nulls_first? = true
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/empty_page.rb b/lib/json_api_kit/pagination/empty_page.rb
new file mode 100644
index 00000000000..c653c5d79bb
--- /dev/null
+++ b/lib/json_api_kit/pagination/empty_page.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class EmptyPage
+ def rows = []
+
+ def next = nil
+
+ def previous = nil
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/keyset.rb b/lib/json_api_kit/pagination/keyset.rb
new file mode 100644
index 00000000000..955622a3e95
--- /dev/null
+++ b/lib/json_api_kit/pagination/keyset.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Keyset
+ attr_reader :keys
+
+ delegate :valued_condition, :null_condition, :nulls_read_first?, to: :leading
+
+ def initialize(keys)
+ @keys = keys.uniq(&:name)
+ raise ArgumentError, "an order needs at least one key" if @keys.empty?
+ end
+
+ def leading = keys.first
+
+ def rest = self.class.new(keys.drop(1))
+
+ def split? = leading.nullable?
+
+ def without_nulls = self.class.new([leading.without_nulls, *keys.drop(1)])
+
+ def columns = keys.reject(&:projected?).map(&:name)
+
+ def order = keys.map(&:ordering)
+
+ def joins = keys.map(&:joins).reduce(:+)
+
+ def reverse = self.class.new(keys.map(&:reverse))
+
+ def values_for(record) = keys.map { Cursor.coerce(it.value_for(record)) }
+
+ def compatible_with?(values) = values.size == keys.size
+
+ def project(scope)
+ return scope if projections.empty?
+
+ model = scope.klass
+ model.unscoped.select(Arel.star).from(subquery(scope), model.table_name)
+ end
+
+ private
+
+ def subquery(scope)
+ selection = scope.select_values.presence || [scope.klass.arel_table[Arel.star]]
+ joins.apply(scope).reselect(*selection, *projections)
+ end
+
+ def projections = @projections ||= keys.filter_map(&:select_expression)
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/keyset/key.rb b/lib/json_api_kit/pagination/keyset/key.rb
new file mode 100644
index 00000000000..dffcc26d4cf
--- /dev/null
+++ b/lib/json_api_kit/pagination/keyset/key.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Keyset
+ class Key
+ attr_reader :name, :model, :direction, :sql, :joins
+
+ delegate :connection, :table_name, :type_for_attribute, to: :model, private: true
+ delegate :quote_table_name, :quote_column_name, to: :connection, private: true
+ delegate :operator, to: :direction
+ delegate :trailing?, :read_first?, to: :nulls, prefix: true
+
+ def initialize(name, model:, direction: :asc, sql: nil, joins: [], nulls: nil)
+ @name = name.to_sym
+ @model = model
+ @direction = Direction.for(direction)
+ @sql = sql
+ @joins = Joins.for(joins)
+ @nulls = Nulls.for(nulls, direction: @direction)
+ end
+
+ def nullable? = nulls.expected?
+
+ def projected? = sql.present?
+
+ def reverse = with(direction: direction.other_way, nulls: nulls.other_end)
+
+ def without_nulls = with(nulls: nil)
+
+ def ordering
+ Arel.sql("#{identifier} #{direction.to_sql}#{nulls.to_sql}")
+ end
+
+ def valued_condition = ->(scope) { joins.apply(scope).where("#{value_sql} IS NOT NULL") }
+
+ def null_condition = ->(scope) { joins.apply(scope).where("#{value_sql} IS NULL") }
+
+ def value_for(record) = record.public_send(name)
+
+ def named?(other) = name.to_s == other.to_s
+
+ def to_s = name.to_s
+
+ def identifier = "#{quoted_table}.#{quoted_name}"
+
+ def value_sql = sql || identifier
+
+ def at_or_after(scope, value) = scope.where("#{value_sql} #{operator}= ?", cast(value))
+
+ def cast(value) = type_for_attribute(name).cast(value)
+
+ def select_expression
+ return unless projected?
+ "#{value_sql} AS #{quoted_name}"
+ end
+
+ private
+
+ attr_reader :nulls
+
+ def with(**changes)
+ self.class.new(
+ name,
+ model:,
+ direction: direction.to_sym,
+ sql:,
+ joins:,
+ nulls: nulls.placement,
+ **changes,
+ )
+ end
+
+ def quoted_table = quote_table_name(table_name)
+
+ def quoted_name = quote_column_name(name)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/nulls.rb b/lib/json_api_kit/pagination/nulls.rb
new file mode 100644
index 00000000000..1eebaca4561
--- /dev/null
+++ b/lib/json_api_kit/pagination/nulls.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Nulls
+ def self.for(placement, direction:)
+ case placement
+ when nil
+ Undeclared.new(direction)
+ when :last
+ Last.new
+ when :first
+ First.new
+ else
+ raise ArgumentError, "unknown nulls: #{placement}"
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/nulls/first.rb b/lib/json_api_kit/pagination/nulls/first.rb
new file mode 100644
index 00000000000..b01394de43f
--- /dev/null
+++ b/lib/json_api_kit/pagination/nulls/first.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Nulls
+ class First < Nulls
+ def expected? = true
+
+ def placement = :first
+
+ def to_sql = " NULLS FIRST"
+
+ def other_end = :last
+
+ def trailing? = false
+
+ def read_first? = true
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/nulls/last.rb b/lib/json_api_kit/pagination/nulls/last.rb
new file mode 100644
index 00000000000..236d8bacce8
--- /dev/null
+++ b/lib/json_api_kit/pagination/nulls/last.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Nulls
+ class Last < Nulls
+ def expected? = true
+
+ def placement = :last
+
+ def to_sql = " NULLS LAST"
+
+ def other_end = :first
+
+ def trailing? = true
+
+ def read_first? = false
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/nulls/undeclared.rb b/lib/json_api_kit/pagination/nulls/undeclared.rb
new file mode 100644
index 00000000000..a208a78d631
--- /dev/null
+++ b/lib/json_api_kit/pagination/nulls/undeclared.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Nulls
+ class Undeclared < Nulls
+ def initialize(direction)
+ @direction = direction
+ end
+
+ def expected? = false
+
+ def placement = nil
+
+ def to_sql = ""
+
+ def other_end = nil
+
+ def trailing? = false
+
+ def read_first? = direction.nulls_first?
+
+ private
+
+ attr_reader :direction
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/numbered_rows.rb b/lib/json_api_kit/pagination/numbered_rows.rb
new file mode 100644
index 00000000000..b146150dd57
--- /dev/null
+++ b/lib/json_api_kit/pagination/numbered_rows.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class NumberedRows
+ ROW_NUMBER = "json_api_kit_row_number"
+
+ def initialize(scope, owner_key:, keyset:, size:)
+ @scope = scope
+ @owner_key = owner_key
+ @keyset = keyset
+ @size = size
+ end
+
+ def bounded_scope
+ scope
+ .model
+ .unscoped
+ .from(numbered_scope, table_name)
+ .where(row_number.lteq(size + 1))
+ .select(*selected_columns)
+ end
+
+ private
+
+ attr_reader :scope, :owner_key, :keyset, :size
+
+ def numbered_scope = scope.reselect(*selected_columns, number_rows)
+
+ def selected_columns
+ @selected_columns ||=
+ scope.select_values.presence || scope.model.column_names.map { column(it) }
+ end
+
+ def number_rows
+ Arel::Nodes::NamedFunction.new("ROW_NUMBER", []).over(window).as(ROW_NUMBER)
+ end
+
+ def window = Arel::Nodes::Window.new.partition(column(owner_key)).order(keyset.order)
+
+ def row_number = Arel::Table.new(table_name)[ROW_NUMBER]
+
+ def column(name) = scope.arel_table[name]
+
+ def table_name = scope.arel_table.name
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/order.rb b/lib/json_api_kit/pagination/order.rb
new file mode 100644
index 00000000000..c1253b297c5
--- /dev/null
+++ b/lib/json_api_kit/pagination/order.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Order
+ attr_reader :segments
+
+ delegate :leading, to: :keyset
+ delegate :first, :columns, :locate, to: :segments
+ delegate :fetch, :after, to: :segments
+
+ def initialize(keyset, type: nil)
+ @type = type
+ @keyset = keyset
+ @segments = Segments.for(keyset, digest:)
+ end
+
+ def reverse = self.class.new(keyset.reverse, type:)
+
+ def digest
+ @digest ||= Digest::SHA256.hexdigest("#{type}:#{keyset.keys.join(",")}").first(8)
+ end
+
+ def position(cursor) = Position.from(cursor, order: self)
+
+ def compatible_with?(cursor:)
+ position(cursor)
+ true
+ rescue KeyError, ArgumentError
+ false
+ end
+
+ def split? = segments.size > 1
+
+ def enter(scope, at_or_after:)
+ locate(at_or_after) || segments.after_every_value_of(leading.name).locate(scope)
+ end
+
+ private
+
+ attr_reader :keyset, :type
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/order/position.rb b/lib/json_api_kit/pagination/order/position.rb
new file mode 100644
index 00000000000..7470113e664
--- /dev/null
+++ b/lib/json_api_kit/pagination/order/position.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Order
+ class Position
+ attr_reader :segment, :values
+
+ def self.from(cursor, order:)
+ digest, segment_id, *values = cursor.values
+ unless digest == order.digest
+ raise ArgumentError, "a cursor comes from one resource and one sort"
+ end
+ new(segment: order.fetch(segment_id), values:)
+ end
+
+ def initialize(segment:, values:)
+ unless segment.compatible_with?(values)
+ raise ArgumentError, "a position holds one value for each key its segment compares"
+ end
+
+ @segment = segment
+ @values = values
+ end
+
+ def to_cursor = Cursor.new([segment.digest, segment.id, *values])
+
+ def in(order) = order.position(to_cursor)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/order/segment.rb b/lib/json_api_kit/pagination/order/segment.rb
new file mode 100644
index 00000000000..85e2b1fbf36
--- /dev/null
+++ b/lib/json_api_kit/pagination/order/segment.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Order
+ class Segment
+ NO_CONDITION = ->(scope) { scope }
+
+ def self.split(keyset, digest: nil, id: 0)
+ return [new(id:, keyset:, digest:)] unless keyset.split?
+
+ valued =
+ new(id:, keyset: keyset.without_nulls, digest:, condition: keyset.valued_condition)
+ nulls =
+ split(keyset.rest, digest:, id: id + 1).map { it.narrowed_by(keyset.null_condition) }
+ keyset.nulls_read_first? ? [*nulls, valued] : [valued, *nulls]
+ end
+
+ attr_reader :id, :keyset, :digest
+
+ delegate :columns, :compatible_with?, to: :keyset
+
+ def initialize(id:, keyset:, digest: nil, condition: NO_CONDITION)
+ @id = id
+ @keyset = keyset
+ @digest = digest
+ @condition = condition
+ end
+
+ def scope(scope) = condition.call(scope)
+
+ def position_of(record) = Position.new(segment: self, values: keyset.values_for(record))
+
+ def led_by?(name) = keyset.leading.named?(name)
+
+ def reverse = self.class.new(id:, keyset: keyset.reverse, digest:, condition:)
+
+ def narrowed_by(other) =
+ self.class.new(id:, keyset:, digest:, condition: condition_after(other))
+
+ private
+
+ attr_reader :condition
+
+ def condition_after(other) = ->(scope) { condition.call(other.call(scope)) }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/order/segments.rb b/lib/json_api_kit/pagination/order/segments.rb
new file mode 100644
index 00000000000..b658737c76e
--- /dev/null
+++ b/lib/json_api_kit/pagination/order/segments.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Order
+ class Segments
+ include Enumerable
+
+ delegate :each, :size, :last, :empty?, to: :segments
+
+ def self.for(keyset, digest: nil) = new(Segment.split(keyset, digest:))
+
+ def initialize(segments)
+ @segments = segments
+ end
+
+ def fetch(id)
+ detect { it.id == id } or raise KeyError, "This listing has no segment #{id.inspect}."
+ end
+
+ def after(segment) = self.class.new(segments.drop(place_of(segment) + 1))
+
+ def after_every_value_of(name) = after(led_by(name))
+
+ def locate(scope)
+ lazy.filter_map { Scan.new(scope, segment: it, size: 1).rows.first }.first
+ end
+
+ def columns = flat_map(&:columns).uniq
+
+ private
+
+ attr_reader :segments
+
+ def led_by(name) = detect { it.led_by?(name) }
+
+ def place_of(segment) = segments.index { it.id == segment.id }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/page_per_owner.rb b/lib/json_api_kit/pagination/page_per_owner.rb
new file mode 100644
index 00000000000..067cf679e64
--- /dev/null
+++ b/lib/json_api_kit/pagination/page_per_owner.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class PagePerOwner
+ SplitOrder = Class.new(StandardError)
+
+ def initialize(scope, order:, size:, owner_key:)
+ @scope = scope
+ @order = order
+ @size = size
+ @owner_key = owner_key
+ verify_one_segment
+ end
+
+ def rows
+ @rows ||=
+ keyset
+ .project(segment.scope(numbered_scope))
+ .reorder(keyset.order)
+ .map { Row.new(record: it, segment:) }
+ end
+
+ def next = nil
+
+ def previous = nil
+
+ private
+
+ attr_reader :scope, :order, :size, :owner_key
+
+ def segment = order.first
+
+ def keyset = segment.keyset
+
+ def numbered_scope = NumberedRows.new(scope, owner_key:, keyset:, size:).bounded_scope
+
+ def verify_one_segment
+ return unless order.split?
+ raise SplitOrder,
+ "a relationship is read one page for each owner, and #{order.leading.name} can " \
+ "be null. Declare a default sort on a column that cannot be null."
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/paginator.rb b/lib/json_api_kit/pagination/paginator.rb
new file mode 100644
index 00000000000..decc82f9348
--- /dev/null
+++ b/lib/json_api_kit/pagination/paginator.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Paginator
+ def self.for(scope, order:, size:, after: nil, before: nil)
+ raise ArgumentError, "a page is read from one end or the other" if after && before
+ return Backwards.new(scope, order:, size:, from: order.position(before)) if before
+ Forwards.new(scope, order:, size:, from: after && order.position(after))
+ end
+
+ def initialize(scope, order:, size:, from: nil)
+ @scope = scope
+ @order = order
+ @size = size
+ @from = from
+ end
+
+ def rows = window.rows
+
+ private
+
+ attr_reader :scope, :order, :size, :from
+
+ def page_order = order
+
+ def window = @window ||= Window.new(scope, order: page_order, size:, after: position)
+
+ def position = @position ||= from&.in(page_order)
+
+ def page_ahead
+ return unless window.truncated?
+ exit_position.to_cursor
+ end
+
+ def page_behind
+ return unless from
+ return unless probe.truncated?
+ entry_position.to_cursor
+ end
+
+ def probe
+ Window.new(scope, order: backwards, size: 0, after: entry_position.in(backwards))
+ end
+
+ def backwards = @backwards ||= page_order.reverse
+
+ def exit_position = window.rows.last&.position || position
+
+ def entry_position = window.rows.first&.position || position
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/paginator/backwards.rb b/lib/json_api_kit/pagination/paginator/backwards.rb
new file mode 100644
index 00000000000..3587c8ce1a2
--- /dev/null
+++ b/lib/json_api_kit/pagination/paginator/backwards.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Paginator
+ class Backwards < Paginator
+ def rows = super.reverse
+
+ def next = page_behind
+
+ def previous = page_ahead
+
+ private
+
+ def page_order = @page_order ||= order.reverse
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/paginator/forwards.rb b/lib/json_api_kit/pagination/paginator/forwards.rb
new file mode 100644
index 00000000000..fdd1810912f
--- /dev/null
+++ b/lib/json_api_kit/pagination/paginator/forwards.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Paginator
+ class Forwards < Paginator
+ def next = page_ahead
+
+ def previous = page_behind
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/predicate.rb b/lib/json_api_kit/pagination/predicate.rb
new file mode 100644
index 00000000000..aee839ebcb7
--- /dev/null
+++ b/lib/json_api_kit/pagination/predicate.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Predicate
+ def initialize(keyset, values)
+ raise ArgumentError, "a split order is read one segment at a time" if keyset.split?
+
+ @terms = keyset.keys.zip(values).map { Term.for(*it) }
+ end
+
+ def sql
+ return row_wise_comparison if row_wise?
+ bound_by_leading_key(disjuncts.join(" OR "))
+ end
+
+ def bindings = terms.map(&:bindings).reduce({}, :merge)
+
+ def apply(scope) = scope.where(sql, bindings)
+
+ private
+
+ attr_reader :terms
+
+ def row_wise?
+ terms.many? && terms.all?(&:comparable?) && terms.map(&:operator).uniq.one?
+ end
+
+ def row_wise_comparison
+ "(#{terms.map(&:identifier).join(", ")}) #{leading.operator} " \
+ "(#{terms.map(&:placeholder).join(", ")})"
+ end
+
+ def disjuncts
+ prefixes.reverse_each.flat_map do |prefix|
+ *matched, moved = prefix
+ moved.disjuncts(matched)
+ end
+ end
+
+ def prefixes = 1.upto(terms.size).map { terms.first(it) }
+
+ def bound_by_leading_key(comparison)
+ return comparison if terms.one?
+ leading.bound_on(comparison)
+ end
+
+ def leading = terms.first
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/predicate/term.rb b/lib/json_api_kit/pagination/predicate/term.rb
new file mode 100644
index 00000000000..f2ec3b9ffec
--- /dev/null
+++ b/lib/json_api_kit/pagination/predicate/term.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Predicate
+ class Term
+ delegate :identifier, :operator, to: :key
+ delegate :name, :nulls_trailing?, :nulls_read_first?, to: :key, private: true
+
+ def self.for(key, value) = value.nil? ? Null.new(key) : new(key, value)
+
+ def initialize(key, value)
+ @key = key
+ @value = value
+ end
+
+ def comparable? = !nulls_trailing?
+
+ def placeholder = ":#{name}"
+
+ def matches = "#{identifier} = #{placeholder}"
+
+ def disjuncts(matched) = ["(#{(matched.map(&:matches) << sorts_after).join(" AND ")})"]
+
+ def bound_on(comparison) = "#{at_or_after_value} AND (#{comparison})"
+
+ def bindings = { name => key.cast(value) }
+
+ private
+
+ attr_reader :key, :value
+
+ def sorts_after
+ return after_value unless nulls_trailing?
+ "(#{after_value} OR #{identifier} IS NULL)"
+ end
+
+ def after_value = "#{identifier} #{operator} #{placeholder}"
+
+ def at_or_after_value = "#{identifier} #{operator}= #{placeholder}"
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/predicate/term/null.rb b/lib/json_api_kit/pagination/predicate/term/null.rb
new file mode 100644
index 00000000000..fe9e53e9990
--- /dev/null
+++ b/lib/json_api_kit/pagination/predicate/term/null.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Predicate
+ class Term
+ class Null < Term
+ def initialize(key) = super(key, nil)
+
+ def comparable? = false
+
+ def matches = "#{identifier} IS NULL"
+
+ def disjuncts(matched)
+ return super if nulls_read_first?
+ []
+ end
+
+ def bound_on(comparison) = comparison
+
+ def bindings = {}
+
+ private
+
+ def sorts_after = "#{identifier} IS NOT NULL"
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/row.rb b/lib/json_api_kit/pagination/row.rb
new file mode 100644
index 00000000000..343134133f4
--- /dev/null
+++ b/lib/json_api_kit/pagination/row.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Row
+ attr_reader :record
+
+ def initialize(record:, segment:)
+ @record = record
+ @segment = segment
+ end
+
+ def position = @position ||= segment.position_of(record)
+
+ def cursor = position.to_cursor
+
+ private
+
+ attr_reader :segment
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/scan.rb b/lib/json_api_kit/pagination/scan.rb
new file mode 100644
index 00000000000..9321e7aa8b1
--- /dev/null
+++ b/lib/json_api_kit/pagination/scan.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Scan
+ def initialize(scope, segment:, size:, after: nil)
+ @scope = scope
+ @segment = segment
+ @size = size
+ @after = after
+ end
+
+ def rows = @rows ||= records.first(size).map { Row.new(record: it, segment:) }
+
+ def truncated? = records.size > size
+
+ private
+
+ attr_reader :scope, :segment, :size, :after
+
+ def keyset = segment.keyset
+
+ def records = @records ||= page_scope.to_a
+
+ def page_scope
+ return ordered_scope unless after
+ Predicate.new(keyset, after).apply(ordered_scope)
+ end
+
+ def ordered_scope = held_scope.reorder(keyset.order).limit(size + 1)
+
+ def held_scope = keyset.project(segment.scope(scope))
+ end
+ end
+end
diff --git a/lib/json_api_kit/pagination/window.rb b/lib/json_api_kit/pagination/window.rb
new file mode 100644
index 00000000000..1b80f331cc9
--- /dev/null
+++ b/lib/json_api_kit/pagination/window.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Pagination
+ class Window
+ def initialize(scope, order:, size:, after: nil)
+ @scope = scope
+ @order = order
+ @size = size
+ @after = after
+ end
+
+ def rows = @rows ||= scans.flat_map(&:rows)
+
+ def truncated? = scans.last.truncated?
+
+ private
+
+ attr_reader :scope, :order, :size, :after
+
+ def scans = @scans ||= read_from(starting_segment, size:, after: after&.values)
+
+ def read_from(segment, size:, after:)
+ scan = Scan.new(scope, segment:, size:, after:)
+ return [scan] if scan.truncated?
+
+ segment_after = order.after(segment).first
+ return [scan] unless segment_after
+ [scan, *read_from(segment_after, size: size - scan.rows.size, after: nil)]
+ end
+
+ def starting_segment = after&.segment || order.first
+ end
+ end
+end
diff --git a/lib/json_api_kit/path.rb b/lib/json_api_kit/path.rb
new file mode 100644
index 00000000000..e93b5b40b21
--- /dev/null
+++ b/lib/json_api_kit/path.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Path
+ SEPARATOR = "."
+
+ def self.for(path) = path.try(:to_path) || new(path.to_s.split(SEPARATOR))
+
+ def initialize(names, at: 0)
+ @names = names
+ @at = at
+ end
+
+ def to_path = self
+
+ def current = names[at]
+
+ def last? = at == names.size - 1
+
+ def entered? = at.positive?
+
+ def next
+ return if last?
+ self.class.new(names, at: at + 1)
+ end
+
+ def to_s = names.join(SEPARATOR)
+
+ def ==(other) = other.is_a?(self.class) && names == other.names && at == other.at
+
+ alias eql? ==
+
+ def hash = [names, at].hash
+
+ protected
+
+ attr_reader :names, :at
+ end
+end
diff --git a/lib/json_api_kit/paths.rb b/lib/json_api_kit/paths.rb
new file mode 100644
index 00000000000..ace864c4135
--- /dev/null
+++ b/lib/json_api_kit/paths.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Paths
+ include Enumerable
+
+ def initialize(paths)
+ @paths = Array(paths).compact_blank.map { Path.for(it) }
+ end
+
+ delegate :each, :empty?, to: :paths
+
+ def +(other) = self.class.new(to_a + other.to_a)
+
+ def relationship_names = map(&:current).uniq
+
+ def next_for(name) = self.class.new(select { it.current == name }.filter_map(&:next))
+
+ private
+
+ attr_reader :paths
+ end
+end
diff --git a/lib/json_api_kit/query.rb b/lib/json_api_kit/query.rb
new file mode 100644
index 00000000000..f6082a37e65
--- /dev/null
+++ b/lib/json_api_kit/query.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Query
+ def initialize(resource, request, scoped_to: nil)
+ @resource = resource
+ @request = request
+ @scoped_to = scoped_to
+ end
+
+ def rows = page.rows
+
+ def records
+ @records ||=
+ Records.new(
+ rows.map do
+ Record.new(it, fields, type: resource.type, relationships: sideloads.linkage_for(it))
+ end,
+ )
+ end
+
+ def included = Included.for(records)
+
+ delegate :item_cursors?, to: :request
+
+ private
+
+ attr_reader :resource, :request, :scoped_to
+
+ delegate :guardian, to: :request, private: true
+
+ def page = @page ||= scoping.page(request.page).paginate(scope, order:, limits:, anchors:)
+
+ def limits = resource.page_limits
+
+ def anchors = resource.anchors(guardian)
+
+ def scope = columns.apply(scoping.apply(filtered_scope))
+
+ def scoping = @scoping ||= Scoping.for(scoped_to)
+
+ def columns
+ fields.columns.with(*order.columns, *owner_keys, *scoping.pairing_keys, primary_key)
+ end
+
+ def owner_keys = relationships.map { schema.owner_key(it.name.to_sym) }
+
+ def primary_key = schema.primary_key
+
+ def schema = @schema ||= resource.schema
+
+ def fields = @fields ||= resource.fields(request.fields[resource.type])
+
+ def sideloads
+ @sideloads ||= Sideloads.for(relationships, paths:, rows:, request:, schema:)
+ end
+
+ def relationships = @relationships ||= fields.relationships.pick(paths.relationship_names)
+
+ def paths = @paths ||= resource.allow(request.including)
+
+ def filtered_scope = resource.apply_filters(available_scope, request.filtering)
+
+ def available_scope = request.scope(from: resource.scope_for(guardian))
+
+ def order = @order ||= resource.order(request.ordering)
+ end
+end
diff --git a/lib/json_api_kit/query/collection.rb b/lib/json_api_kit/query/collection.rb
new file mode 100644
index 00000000000..0bd5cc3be46
--- /dev/null
+++ b/lib/json_api_kit/query/collection.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Query
+ class Collection < Query
+ def pages = { before: previous, after: self.next }
+
+ def next = page.next&.to_s
+
+ def previous = page.previous&.to_s
+ end
+ end
+end
diff --git a/lib/json_api_kit/query/individual.rb b/lib/json_api_kit/query/individual.rb
new file mode 100644
index 00000000000..dee13ec7df9
--- /dev/null
+++ b/lib/json_api_kit/query/individual.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Query
+ class Individual < Query
+ def record
+ records.first or raise NotFound
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/record.rb b/lib/json_api_kit/record.rb
new file mode 100644
index 00000000000..029265a87a2
--- /dev/null
+++ b/lib/json_api_kit/record.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Record
+ Identity = Data.define(:type, :id)
+
+ delegate :record, :cursor, to: :row
+
+ attr_reader :type, :relationships
+
+ def initialize(row, fields, type:, relationships: {})
+ @row = row
+ @fields = fields
+ @type = type
+ @relationships = relationships
+ end
+
+ def id = @id ||= record.id.to_s
+
+ def identity = @identity ||= Identity.new(type:, id:)
+
+ def attributes = fields.attributes.values_for(record)
+
+ def merge(other)
+ self.class.new(row, fields, type:, relationships: other.relationships.merge(relationships))
+ end
+
+ def related_records = relationships.values.flat_map(&:records)
+
+ private
+
+ attr_reader :row, :fields
+ end
+end
diff --git a/lib/json_api_kit/records.rb b/lib/json_api_kit/records.rb
new file mode 100644
index 00000000000..0fb4f63f49f
--- /dev/null
+++ b/lib/json_api_kit/records.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Records
+ include Enumerable
+
+ class Page
+ attr_reader :records, :cursor
+
+ def initialize(records, cursor)
+ @records = records
+ @cursor = cursor
+ end
+ end
+
+ delegate :each, :size, :empty?, :to_ary, to: :records
+
+ def initialize(records)
+ @records = records
+ end
+
+ def page(size) = Page.new(self.class.new(records.first(size)), cursor_after(size))
+
+ def fetch_all(rows) = self.class.new(rows.map { by_record.fetch(it) })
+
+ private
+
+ attr_reader :records
+
+ def by_record = @by_record ||= records.index_by(&:record)
+
+ def cursor_after(size)
+ return if records.size <= size
+ records[size - 1].cursor
+ end
+ end
+end
diff --git a/lib/json_api_kit/reflection.rb b/lib/json_api_kit/reflection.rb
new file mode 100644
index 00000000000..54d574564f5
--- /dev/null
+++ b/lib/json_api_kit/reflection.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Reflection
+ def self.for(reflection)
+ return Through.new(reflection) if reflection.through_reflection?
+ new(reflection)
+ end
+
+ delegate :belongs_to?,
+ :foreign_key,
+ :association_primary_key,
+ :active_record_primary_key,
+ :klass,
+ to: :reflection,
+ private: true
+
+ def initialize(reflection)
+ @reflection = reflection
+ end
+
+ def owner_key = keys.fetch(:owner_key).to_sym
+
+ def association(owner_records) = Association.new(scope:, owner_records:, **keys)
+
+ private
+
+ attr_reader :reflection
+
+ def keys
+ return keys_on_owner_row if belongs_to?
+ keys_on_related_row
+ end
+
+ def keys_on_owner_row = { owner_key: foreign_key, related_key: association_primary_key }
+
+ def keys_on_related_row = { owner_key: active_record_primary_key, related_key: foreign_key }
+
+ def scope
+ rows = klass.all
+ return rows unless reflection.scope
+ rows.merge(reflection.scope)
+ end
+ end
+end
diff --git a/lib/json_api_kit/reflection/through.rb b/lib/json_api_kit/reflection/through.rb
new file mode 100644
index 00000000000..da1abc4cf58
--- /dev/null
+++ b/lib/json_api_kit/reflection/through.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Reflection
+ class Through < Reflection
+ delegate :through_reflection, :source_reflection, to: :reflection, private: true
+
+ def owner_key = active_record_primary_key.to_sym
+
+ def association(owner_records)
+ Association::Through.new(
+ scope:,
+ owner_records:,
+ owner_key:,
+ related_key: association_primary_key,
+ join_scope:,
+ join_owner_key:,
+ join_related_key:,
+ )
+ end
+
+ private
+
+ def join_scope = through_reflection.klass.all
+
+ def join_owner_key = through_reflection.foreign_key
+
+ def join_related_key = source_reflection.foreign_key
+ end
+ end
+end
diff --git a/lib/json_api_kit/request.rb b/lib/json_api_kit/request.rb
new file mode 100644
index 00000000000..d0fe0c7f713
--- /dev/null
+++ b/lib/json_api_kit/request.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ attr_reader :guardian
+
+ def initialize(params = {}, guardian:)
+ @params = ActiveSupport::HashWithIndifferentAccess.new(params)
+ @page_params = @params[:page].to_h.symbolize_keys
+ @guardian = guardian
+ end
+
+ def ordering = @ordering ||= params[:sort].to_h.transform_values(&:to_sym)
+
+ def filtering = @filtering ||= params[:filter].to_h
+
+ def fields = @fields ||= params[:fields].to_h.transform_values { it.map(&:to_s) }
+
+ def including = @including ||= Paths.new(params[:include])
+
+ def for_sideload(paths) = { fields:, include: paths }
+
+ def page = @page ||= Page::Requested.for(anchoring:, **paging)
+
+ def anchoring = @anchoring ||= Anchoring.for(page_params[:anchor])
+
+ def item_cursors? = page_params[:item_cursors].present?
+
+ private
+
+ attr_reader :params, :page_params
+
+ def paging
+ page_params
+ .except(:item_cursors, :anchor)
+ .merge(after: cursor(:after), before: cursor(:before))
+ .compact
+ end
+
+ def cursor(name)
+ return unless page_params[name]
+ Pagination::Cursor.parse(page_params[name])
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/collection.rb b/lib/json_api_kit/request/collection.rb
new file mode 100644
index 00000000000..d3a63fbd509
--- /dev/null
+++ b/lib/json_api_kit/request/collection.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Collection < Request
+ def scope(from:) = from
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract.rb b/lib/json_api_kit/request/contract.rb
new file mode 100644
index 00000000000..c053eaed075
--- /dev/null
+++ b/lib/json_api_kit/request/contract.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract < Service::ContractBase
+ module RawAttributes
+ extend ActiveSupport::Concern
+
+ included { attribute_method_suffix "_before_type_cast", parameters: false }
+
+ def attribute_before_type_cast(name) = raw_attributes[name]
+ end
+
+ class IndifferentHashType < ActiveModel::Type::Value
+ def cast_value(value)
+ value.with_indifferent_access if value.is_a?(Hash)
+ end
+ end
+
+ INDIFFERENT_HASH = IndifferentHashType.new
+
+ include RawAttributes
+
+ validate :check_shapes
+ validate :check_unknown_parameters
+
+ def read_attribute_for_validation(name)
+ return unless respond_to?(name)
+ super
+ end
+
+ private
+
+ def resource = options[:resource]
+
+ def raw_parameters = options[:raw_parameters]
+
+ def comparable?(value) = !value.is_a?(Enumerable)
+
+ def refuse_unknown(attribute, names)
+ names.each { errors.add(attribute, :no_such_name, name: it, message: "no such name") }
+ end
+
+ def check_shapes
+ self.class.attribute_types.each do |name, type|
+ next unless type.is_a?(IndifferentHashType) || type.is_a?(Service::NestedContractType)
+ next if attribute_before_type_cast(name).nil? || !public_send(name).nil?
+ errors.add(name, :bad_shape, message: "bad shape")
+ end
+ end
+
+ def check_unknown_parameters = check_parameters(raw_parameters, self.class)
+
+ def check_parameters(parameters, contract, prefix = nil)
+ (parameters.keys - contract.attribute_names).each do |name|
+ errors.add(
+ [prefix, name].compact.join(".").to_sym,
+ :unknown_parameter,
+ message: "unknown parameter",
+ )
+ end
+ contract.attribute_types.each do |name, type|
+ next unless type.is_a?(Service::NestedContractType) && attributes[name]
+ check_parameters(parameters[name], type.contract_class, name)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/collection.rb b/lib/json_api_kit/request/contract/collection.rb
new file mode 100644
index 00000000000..0683f470164
--- /dev/null
+++ b/lib/json_api_kit/request/contract/collection.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ class Collection < Contract
+ include Fields
+ include Including
+ include Sorting
+ include Filtering
+ include Paging
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/error.rb b/lib/json_api_kit/request/contract/error.rb
new file mode 100644
index 00000000000..beb51a249a9
--- /dev/null
+++ b/lib/json_api_kit/request/contract/error.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ class Error < BadRequest
+ def initialize(error, title:, detail: nil, source: nil, type: nil, meta: nil)
+ @error = error
+ @title = title
+ @detail = detail
+ @source = source
+ @type = type
+ @meta = meta
+ super()
+ end
+
+ attr_reader :title, :type
+
+ delegate :options, :base, to: :error
+
+ def detail = @detail&.call(self) || error.message
+
+ def source = { parameter: @source&.call(self) || parameter }
+
+ def meta = @meta&.call(self) || {}
+
+ def parameter
+ name, *nested = error.attribute.to_s.split(".")
+ nested.reduce(name) { |named, part| "#{named}[#{part}]" }
+ end
+
+ private
+
+ attr_reader :error
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/fields.rb b/lib/json_api_kit/request/contract/fields.rb
new file mode 100644
index 00000000000..d2ffc1b83a4
--- /dev/null
+++ b/lib/json_api_kit/request/contract/fields.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ module Fields
+ extend ActiveSupport::Concern
+
+ included do
+ attribute :fields, INDIFFERENT_HASH
+
+ validate :check_fields, if: -> { fields.present? }
+ end
+
+ private
+
+ def check_fields
+ fields.each_key do |type|
+ next if fields[type].is_a?(Array)
+ errors.add(:fields, :bad_value, name: type, message: "bad value")
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/filtering.rb b/lib/json_api_kit/request/contract/filtering.rb
new file mode 100644
index 00000000000..8bf1c63586f
--- /dev/null
+++ b/lib/json_api_kit/request/contract/filtering.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ module Filtering
+ extend ActiveSupport::Concern
+
+ included do
+ attribute :filter, INDIFFERENT_HASH
+
+ validate :check_filter_names, if: -> { filter.present? }
+ validate :check_filter_values, if: -> { filter.present? }
+ end
+
+ private
+
+ def check_filter_names = refuse_unknown(:filter, filter.keys - resource.filter_names)
+
+ def check_filter_values
+ filter.each_key do |name|
+ next if comparable?(filter[name]) || listed?(filter[name])
+ errors.add(:filter, :bad_value, name:, message: "bad value")
+ end
+ end
+
+ def listed?(value) = Array.wrap(value).all? { comparable?(it) }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/including.rb b/lib/json_api_kit/request/contract/including.rb
new file mode 100644
index 00000000000..058c355dfcf
--- /dev/null
+++ b/lib/json_api_kit/request/contract/including.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ module Including
+ extend ActiveSupport::Concern
+
+ included do
+ attribute :include, default: -> { [] }
+
+ validate :check_include_paths, if: -> { include.present? }
+ end
+
+ private
+
+ def check_include_paths
+ refuse_unknown(:include, Paths.new(include).reject { resource.paths_include?(it) })
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/individual.rb b/lib/json_api_kit/request/contract/individual.rb
new file mode 100644
index 00000000000..68615e7a5e2
--- /dev/null
+++ b/lib/json_api_kit/request/contract/individual.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ class Individual < Contract
+ include Fields
+ include Including
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/mapper.rb b/lib/json_api_kit/request/contract/mapper.rb
new file mode 100644
index 00000000000..308ef1bb46d
--- /dev/null
+++ b/lib/json_api_kit/request/contract/mapper.rb
@@ -0,0 +1,172 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ class Mapper
+ MAX_SIZE = "https://jsonapi.org/profiles/ethanresnick/cursor-pagination/max-size-exceeded"
+ RANGE_UNSUPPORTED =
+ "https://jsonapi.org/profiles/ethanresnick/cursor-pagination/range-pagination-not-supported"
+ NOT_AN_INTEGER = {
+ title: "Page size is not an integer",
+ detail: ->(_) { "Page size must be an integer." },
+ }.freeze
+ RANGE = {
+ title: "Range pagination is not supported",
+ detail: ->(_) { "Use page[after] or page[before], not both." },
+ type: RANGE_UNSUPPORTED,
+ }.freeze
+ INVALID_CURSOR = {
+ title: "Invalid cursor",
+ detail: ->(_) { "Use a cursor from this resource and this sort." },
+ }.freeze
+ SIDE_NOT_AN_INTEGER = {
+ title: "Window size is not an integer",
+ detail: ->(error) { "#{error.parameter} must be an integer." },
+ }.freeze
+ NEGATIVE_SIDE = {
+ title: "Window size is negative",
+ detail: ->(error) { "#{error.parameter} must be 0 or greater." },
+ }.freeze
+ WINDOW_PARAMETER = ->(error) { error.base.page.window_names.first }
+ UNKNOWN_PARAMETER = {
+ title: "No such parameter",
+ detail: ->(error) { "There is no parameter named #{error.parameter}." },
+ }.freeze
+
+ RULES = {
+ [:"page.anchor", :wrong_length] => {
+ title: "Too many anchors",
+ detail: ->(error) do
+ "Use one anchor only. This request has #{error.base.page.anchor.size}."
+ end,
+ },
+ [:"page.anchor", :present] => {
+ title: "Anchor and cursor cannot be combined",
+ detail: ->(error) do
+ "Use page[anchor] or page[#{error.base.page.cursor_name}], not both."
+ end,
+ },
+ [:"page.anchor", :blank] => {
+ title: "Anchor is required",
+ detail: ->(error) { "#{error.base.page.window_names.join(", ")} need an anchor." },
+ },
+ [:"page.anchor", :no_such_name] => {
+ title: "No such anchor",
+ detail: ->(error) { "There is no anchor named #{error.options[:name]}." },
+ source: ->(error) { "page[anchor][#{error.options[:name]}]" },
+ },
+ [:"page.anchor", :not_the_sort] => {
+ title: "Anchor does not match the sort",
+ detail: ->(error) do
+ "The anchor is #{error.options[:name]}, but this request sorts by " \
+ "#{error.options[:key]}."
+ end,
+ source: ->(error) { "page[anchor][#{error.options[:name]}]" },
+ },
+ %i[sort no_such_name] => {
+ title: "No such sort",
+ detail: ->(error) { "There is no sort named #{error.options[:name]}." },
+ },
+ %i[sort unknown_direction] => {
+ title: "No such sort direction",
+ detail: ->(error) { "Sort direction #{error.options[:direction]} is not asc or desc." },
+ },
+ %i[filter no_such_name] => {
+ title: "No such filter",
+ detail: ->(error) { "There is no filter named #{error.options[:name]}." },
+ source: ->(error) { "filter[#{error.options[:name]}]" },
+ },
+ %i[include no_such_name] => {
+ title: "No such relationship path",
+ detail: ->(error) { "There is no relationship path named #{error.options[:name]}." },
+ },
+ %i[fields bad_shape] => {
+ title: "Invalid fields parameter",
+ detail: ->(_) { "fields must name a list of fields for each type." },
+ },
+ %i[fields bad_value] => {
+ title: "Invalid fields value",
+ detail: ->(error) { "fields[#{error.options[:name]}] must be a list of field names." },
+ source: ->(error) { "fields[#{error.options[:name]}]" },
+ },
+ %i[sort bad_shape] => {
+ title: "Invalid sort parameter",
+ detail: ->(_) { "sort must name a direction for each sort." },
+ },
+ %i[filter bad_shape] => {
+ title: "Invalid filter parameter",
+ detail: ->(_) { "filter must name a value for each filter." },
+ },
+ %i[filter bad_value] => {
+ title: "Invalid filter value",
+ detail: ->(error) do
+ "filter[#{error.options[:name]}] must be a value or a list of values."
+ end,
+ source: ->(error) { "filter[#{error.options[:name]}]" },
+ },
+ [:"page.anchor", :bad_value] => {
+ title: "Invalid anchor value",
+ detail: ->(error) { "page[anchor][#{error.options[:name]}] must be a single value." },
+ source: ->(error) { "page[anchor][#{error.options[:name]}]" },
+ },
+ %i[page bad_shape] => {
+ title: "Invalid page parameter",
+ detail: ->(_) { "page must name page parameters, as in page[size]=2." },
+ },
+ [:"page.size", :not_an_integer] => NOT_AN_INTEGER,
+ [:"page.size", :not_a_number] => NOT_AN_INTEGER,
+ [:"page.size", :greater_than] => {
+ title: "Page size is too small",
+ detail: ->(_) { "Page size must be at least 1." },
+ },
+ [:"page.size", :less_than_or_equal_to] => {
+ title: "Page size is too large",
+ detail: ->(error) do
+ "Page size #{error.options[:value]} exceeds the maximum of #{error.options[:count]}."
+ end,
+ type: MAX_SIZE,
+ meta: ->(error) { { page: { maxSize: error.options[:count] } } },
+ },
+ [:"page.before_size", :not_an_integer] => SIDE_NOT_AN_INTEGER,
+ [:"page.before_size", :not_a_number] => SIDE_NOT_AN_INTEGER,
+ [:"page.before_size", :greater_than_or_equal_to] => NEGATIVE_SIDE,
+ [:"page.after_size", :not_an_integer] => SIDE_NOT_AN_INTEGER,
+ [:"page.after_size", :not_a_number] => SIDE_NOT_AN_INTEGER,
+ [:"page.after_size", :greater_than_or_equal_to] => NEGATIVE_SIDE,
+ [:"page.window_size", :greater_than] => {
+ title: "Window is empty",
+ detail: ->(_) { "A window must be at least 1 row." },
+ source: WINDOW_PARAMETER,
+ },
+ [:"page.window_size", :less_than_or_equal_to] => {
+ title: "Window is too large",
+ detail: ->(error) do
+ "A window of #{error.options[:value]} rows exceeds " \
+ "the maximum of #{error.options[:count]}."
+ end,
+ source: WINDOW_PARAMETER,
+ type: MAX_SIZE,
+ meta: ->(error) { { page: { maxSize: error.options[:count] } } },
+ },
+ [:"page.after", :present] => RANGE,
+ [:"page.before", :present] => RANGE,
+ [:"page.after", :unreadable_cursor] => INVALID_CURSOR,
+ [:"page.before", :unreadable_cursor] => INVALID_CURSOR,
+ }.freeze
+
+ def initialize(errors)
+ @errors = errors
+ end
+
+ def to_a = errors.map { Error.new(it, **rule_for(it)) }
+
+ private
+
+ attr_reader :errors
+
+ def rule_for(error) = RULES.fetch([error.attribute, error.type], UNKNOWN_PARAMETER)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/paging.rb b/lib/json_api_kit/request/contract/paging.rb
new file mode 100644
index 00000000000..d7c53b38a30
--- /dev/null
+++ b/lib/json_api_kit/request/contract/paging.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ module Paging
+ extend ActiveSupport::Concern
+
+ class AnchorType < ActiveModel::Type::Value
+ def cast_value(value) = Array(value)
+ end
+
+ included do
+ attribute :page, :hash do
+ include RawAttributes
+
+ delegate :max_page_size, to: :resource
+
+ attribute :size, :integer
+ attribute :after, :string
+ attribute :before, :string
+ attribute :before_size, :integer
+ attribute :after_size, :integer
+ attribute :include_anchor, :boolean
+ attribute :item_cursors, :boolean
+ attribute :anchor, AnchorType.new
+
+ validates :size,
+ numericality: {
+ only_integer: true,
+ greater_than: 0,
+ less_than_or_equal_to: :max_page_size,
+ },
+ unless: -> { size_before_type_cast.nil? }
+ validates :before_size,
+ numericality: {
+ only_integer: true,
+ greater_than_or_equal_to: 0,
+ },
+ unless: -> { before_size_before_type_cast.nil? }
+ validates :after_size,
+ numericality: {
+ only_integer: true,
+ greater_than_or_equal_to: 0,
+ },
+ unless: -> { after_size_before_type_cast.nil? }
+ validates :window_size,
+ numericality: {
+ greater_than: 0,
+ less_than_or_equal_to: :max_page_size,
+ },
+ allow_nil: true
+ validates :after, absence: true, if: -> { before.present? }
+ validates :before, absence: true, if: -> { after.present? }
+ validates :anchor, length: { is: 1 }, allow_nil: true
+ validates :anchor, absence: true, if: -> { cursor? }
+ validates :anchor, presence: true, if: -> { window? }
+
+ validate :check_cursors, if: -> { raw_cursors.present? }
+ validate :check_cursor_ordering,
+ if: -> { cursors.present? && ordering && resource.sortable_by?(ordering:) }
+ validate :check_anchor_name, if: -> { anchor.present? }
+ validate :check_anchor_value, if: -> { anchor.present? }
+ validate :check_anchor_ordering,
+ if: -> { anchor.present? && resource.sortable_by?(ordering:) }
+
+ def cursor? = after.present? || before.present?
+
+ def cursor_name = after.present? ? :after : :before
+
+ def window? = window_names.present?
+
+ def window_names
+ { before_size:, after_size:, include_anchor: }.compact.keys.map { "page[#{it}]" }
+ end
+
+ private
+
+ def cursors
+ raw_cursors
+ .select { |_, raw| Pagination::Cursor.valid?(raw) }
+ .transform_values { Pagination::Cursor.parse(it) }
+ end
+
+ def resource = options[:resource]
+
+ def raw_sort = options[:raw_parameters][:sort]
+
+ def ordering = raw_sort.nil? ? {} : INDIFFERENT_HASH.cast(raw_sort)
+
+ def window_size
+ return unless before_size || after_size
+ before_size.to_i + after_size.to_i + anchor_rows
+ end
+
+ def anchor_rows = include_anchor == false ? 0 : 1
+
+ def raw_cursors = { after:, before: }.compact
+
+ def check_cursors
+ (raw_cursors.keys - cursors.keys).each do
+ errors.add(it, :unreadable_cursor, message: "unreadable cursor")
+ end
+ end
+
+ def check_cursor_ordering
+ cursors
+ .reject { |_, cursor| resource.paged_from?(cursor, ordering:) }
+ .each_key { errors.add(it, :unreadable_cursor, message: "unreadable cursor") }
+ end
+
+ def check_anchor_name
+ ([anchor_name.to_s] - resource.anchor_names).each do
+ errors.add(:anchor, :no_such_name, name: it, message: "no such name")
+ end
+ end
+
+ def check_anchor_value
+ return unless anchor_value.is_a?(Enumerable)
+ errors.add(:anchor, :bad_value, name: anchor_name, message: "bad value")
+ end
+
+ def check_anchor_ordering
+ return if resource.anchored_by?(anchor_name:, ordering:)
+ errors.add(
+ :anchor,
+ :not_the_sort,
+ name: anchor_name,
+ key: resource.order(ordering).leading.name,
+ message: "not the sort",
+ )
+ end
+
+ def anchor_pair = Array(anchor.to_a.first)
+
+ def anchor_name = anchor_pair.first
+
+ def anchor_value = anchor_pair.last
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/sorting.rb b/lib/json_api_kit/request/contract/sorting.rb
new file mode 100644
index 00000000000..fa1d70cc374
--- /dev/null
+++ b/lib/json_api_kit/request/contract/sorting.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ module Sorting
+ extend ActiveSupport::Concern
+
+ DIRECTIONS = %w[asc desc].freeze
+
+ included do
+ attribute :sort, INDIFFERENT_HASH
+
+ validate :check_sort_names, if: -> { sort.present? }
+ validate :check_sort_directions, if: -> { sort.present? }
+ end
+
+ private
+
+ def check_sort_names = refuse_unknown(:sort, sort.keys - resource.sort_names)
+
+ def check_sort_directions
+ sort.each_value do |direction|
+ next if direction.to_s.in?(DIRECTIONS)
+ errors.add(:sort, :unknown_direction, direction:, message: "unknown direction")
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/individual.rb b/lib/json_api_kit/request/individual.rb
new file mode 100644
index 00000000000..241fc98b673
--- /dev/null
+++ b/lib/json_api_kit/request/individual.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Individual < Request
+ def scope(from:) = from.where(from.primary_key => id)
+
+ private
+
+ def id = params[:id]
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource.rb b/lib/json_api_kit/resource.rb
new file mode 100644
index 00000000000..21ef260078f
--- /dev/null
+++ b/lib/json_api_kit/resource.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ include Naming
+ include Sorting
+ include Filtering
+ include Paging
+ include Anchoring
+ include Fields
+ include Including
+ include QueryInterface
+ end
+end
diff --git a/lib/json_api_kit/resource/anchoring.rb b/lib/json_api_kit/resource/anchoring.rb
new file mode 100644
index 00000000000..0404bfb17ca
--- /dev/null
+++ b/lib/json_api_kit/resource/anchoring.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Anchoring
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_anchors,
+ default: [].freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_anchors, :declared_anchors=
+ end
+
+ class_methods do
+ def anchor(name, &condition)
+ self.declared_anchors = declared_anchors + [Declarations::Anchor.new(name, &condition)]
+ end
+
+ def anchor_names = declared_anchors.map(&:name)
+
+ def anchored_by?(anchor_name:, ordering: {})
+ declared_anchors
+ .detect { it.name == anchor_name.to_s }
+ .then { it.nil? || it.locatable_in?(order(ordering)) }
+ end
+
+ def anchors(guardian) = Declarations::Anchors.new(declared_anchors, guardian:)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/fields.rb b/lib/json_api_kit/resource/fields.rb
new file mode 100644
index 00000000000..f4d3cee3a4d
--- /dev/null
+++ b/lib/json_api_kit/resource/fields.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Fields
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_attributes,
+ default: [].freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ class_attribute :declared_relationships,
+ default: [].freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_attributes,
+ :declared_attributes=,
+ :declared_relationships,
+ :declared_relationships=
+ end
+
+ class_methods do
+ delegate :resolves?, to: :relationships
+
+ def attribute(name, &value)
+ self.declared_attributes =
+ declared_attributes + [Declarations::Attribute.new(name, &value)]
+ end
+
+ def has_one(name, resource:)
+ relate(Declarations::Relationship::ToOne.new(name, resource:))
+ end
+
+ def has_many(name, resource:)
+ relate(Declarations::Relationship::ToMany.new(name, resource:))
+ end
+
+ def fields(names = nil)
+ Declarations::Fields.for(
+ names,
+ attributes: declared_attributes,
+ relationships: declared_relationships,
+ schema:,
+ )
+ end
+
+ private
+
+ def relationships = Declarations::Relationships.new(declared_relationships)
+
+ def relate(relationship)
+ self.declared_relationships = declared_relationships + [relationship]
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/filtering.rb b/lib/json_api_kit/resource/filtering.rb
new file mode 100644
index 00000000000..6a8d5b044a6
--- /dev/null
+++ b/lib/json_api_kit/resource/filtering.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Filtering
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_filters,
+ default: [].freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_filters, :declared_filters=
+ end
+
+ class_methods do
+ def filter(name, &condition)
+ self.declared_filters = declared_filters + [Declarations::Filter.new(name, &condition)]
+ end
+
+ def apply_filters(rows, filtering = {}) = filters.apply(rows, filtering)
+
+ def filter_names = declared_filters.map(&:name)
+
+ private
+
+ def filters = Declarations::Filters.new(declared_filters)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/including.rb b/lib/json_api_kit/resource/including.rb
new file mode 100644
index 00000000000..9cf88788f26
--- /dev/null
+++ b/lib/json_api_kit/resource/including.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Including
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_include_paths,
+ default: Paths.new([]).freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_include_paths, :declared_include_paths=
+ end
+
+ class_methods do
+ delegate :allow, to: :include_paths
+ delegate :include?, to: :include_paths, prefix: :paths
+
+ def includes(*paths)
+ self.declared_include_paths = declared_include_paths + Paths.new(paths)
+ end
+
+ private
+
+ def include_paths
+ Declarations::IncludePaths.new(declared_include_paths, relationships:)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/naming.rb b/lib/json_api_kit/resource/naming.rb
new file mode 100644
index 00000000000..d9508a15f95
--- /dev/null
+++ b/lib/json_api_kit/resource/naming.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Naming
+ extend ActiveSupport::Concern
+
+ MissingDeclaration = Class.new(StandardError)
+
+ NAMING = /\A(?<path>(?:\w+::)*(?<subject>\w+))Resource\z/
+ private_constant :NAMING
+
+ included do
+ class_attribute :declared_model,
+ :declared_type,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_model, :declared_model=, :declared_type, :declared_type=
+ end
+
+ class_methods do
+ def model(declaration = nil)
+ return resolved_model unless declaration
+ @resolved_model = nil
+ self.declared_model = declaration
+ end
+
+ def schema = Schema.new(model)
+
+ def type(declaration = nil)
+ return declared_type || inferred_type unless declaration
+ self.declared_type = declaration.to_s
+ end
+
+ private
+
+ def resolved_model = @resolved_model ||= model_for(declared_model || name_parts[:path])
+
+ def model_for(model)
+ model.to_s.camelize.safe_constantize or raise MissingDeclaration, no_model(model)
+ end
+
+ def inferred_type = @inferred_type ||= name_parts[:subject].underscore.pluralize
+
+ def name_parts
+ name&.match(NAMING) or raise MissingDeclaration, nothing_to_infer_from
+ end
+
+ def no_model(model)
+ "#{self}: no model is named #{model.to_s.camelize}, declare it with `model SomeModel`"
+ end
+
+ def nothing_to_infer_from
+ "#{inspect} is not named after what it exposes: declare `model SomeModel` and `type :things`"
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/paging.rb b/lib/json_api_kit/resource/paging.rb
new file mode 100644
index 00000000000..f35dd1b049b
--- /dev/null
+++ b/lib/json_api_kit/resource/paging.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Paging
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_page_limits,
+ default: {}.freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_page_limits, :declared_page_limits=
+ end
+
+ class_methods do
+ def page(default: nil, max: nil)
+ self.declared_page_limits = declared_page_limits.merge({ default:, max: }.compact)
+ page_limits
+ end
+
+ def page_limits = Page::Limits.new(**declared_page_limits)
+
+ def page_size = page_limits.size
+
+ def max_page_size = page_limits.max
+
+ def paged_from?(cursor, ordering: {}) = order(ordering).compatible_with?(cursor:)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/query_interface.rb b/lib/json_api_kit/resource/query_interface.rb
new file mode 100644
index 00000000000..4bd313707f9
--- /dev/null
+++ b/lib/json_api_kit/resource/query_interface.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module QueryInterface
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_scope, instance_accessor: false, instance_predicate: false
+ private_class_method :declared_scope, :declared_scope=
+ end
+
+ class_methods do
+ def scope(&block)
+ self.declared_scope = block
+ end
+
+ def scope_for(guardian)
+ return model.all unless declared_scope
+ declared_scope.call(guardian)
+ end
+
+ def all(params = {}, guardian:, scoped_to: nil)
+ Query::Collection.new(self, Request::Collection.new(params, guardian:), scoped_to:)
+ end
+
+ def find(id, params = {}, guardian:)
+ Query::Individual.new(self, Request::Individual.new(params.merge(id:), guardian:))
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/sorting.rb b/lib/json_api_kit/resource/sorting.rb
new file mode 100644
index 00000000000..1cce7d776ee
--- /dev/null
+++ b/lib/json_api_kit/resource/sorting.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Sorting
+ extend ActiveSupport::Concern
+
+ UndeclaredDefault = Class.new(StandardError)
+
+ included do
+ class_attribute :declared_unique_by, instance_accessor: false, instance_predicate: false
+ class_attribute :declared_sorts,
+ default: [].freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ class_attribute :declared_default_sort,
+ default: {}.freeze,
+ instance_accessor: false,
+ instance_predicate: false
+ private_class_method :declared_sorts,
+ :declared_sorts=,
+ :declared_default_sort,
+ :declared_default_sort=,
+ :declared_unique_by,
+ :declared_unique_by=
+ end
+
+ class_methods do
+ def sort(name, **options)
+ self.declared_sorts = declared_sorts + [Declarations::Sort.for(name, **options)]
+ end
+
+ def default_sort(ordering)
+ verify_sorts(ordering.keys)
+ self.declared_default_sort = ordering
+ end
+
+ def unique_by(*columns)
+ self.declared_unique_by = columns
+ end
+
+ def sort_names = declared_sorts.map(&:name)
+
+ def order(ordering = {}) = Pagination::Order.new(sorts.keyset(ordering), type:)
+
+ def sortable_by?(ordering:) = (ordering.keys - sort_names).empty?
+
+ private
+
+ def sorts
+ Declarations::Sorts.new(
+ declared_sorts,
+ schema:,
+ default: declared_default_sort,
+ unique_by: declared_unique_by,
+ )
+ end
+
+ def verify_sorts(names)
+ missing = names.map(&:to_s) - declared_sorts.map(&:name)
+ raise UndeclaredDefault, no_such_sort(missing) unless missing.empty?
+ end
+
+ def no_such_sort(names)
+ "#{self}: there is no sort named #{names.join(", ")}, " \
+ "declare it with `sort` before naming it as the default"
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/schema.rb b/lib/json_api_kit/schema.rb
new file mode 100644
index 00000000000..4a3fa28795c
--- /dev/null
+++ b/lib/json_api_kit/schema.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Schema
+ MissingAssociation = Class.new(StandardError)
+
+ attr_reader :model
+
+ delegate :reflect_on_association, to: :model, private: true
+
+ def initialize(model)
+ @model = model
+ end
+
+ def table_of(association)
+ reflect_on_association(association).try { it.klass.table_name } or
+ raise MissingAssociation, "#{model}: there is no association named #{association}"
+ end
+
+ def primary_key = model.primary_key.to_sym
+
+ def column(name)
+ return unless columns.key?(name.to_s)
+ name.to_sym
+ end
+
+ def nullable?(name)
+ column = columns[name.to_s]
+ return true unless column
+ column.null
+ end
+
+ def owner_key(name) = reflection_for(name).owner_key
+
+ def association(name, owner_records) = reflection_for(name).association(owner_records)
+
+ private
+
+ def columns = model.columns_hash
+
+ def reflection_for(name) = Reflection.for(reflect_on_association(name))
+ end
+end
diff --git a/lib/json_api_kit/scoping.rb b/lib/json_api_kit/scoping.rb
new file mode 100644
index 00000000000..2930fa6f14b
--- /dev/null
+++ b/lib/json_api_kit/scoping.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Scoping
+ class All < Scoping
+ def initialize = super(nil)
+
+ def apply(scope) = scope
+ end
+
+ class PerOwner < Scoping
+ def initialize(scoped_to, owner_key:)
+ super(scoped_to)
+ @owner_key = owner_key
+ end
+
+ def page(_requested) = Page::PerOwner.new(owner_key)
+
+ def pairing_keys = [owner_key]
+
+ private
+
+ attr_reader :owner_key
+ end
+
+ def self.for(scoped_to)
+ return All.new unless scoped_to
+ scoped_to.try(:to_scoping) || new(scoped_to)
+ end
+
+ def initialize(scoped_to)
+ @scoped_to = scoped_to
+ end
+
+ def to_scoping = self
+
+ def apply(scope)
+ narrowed = scope.merge(scoped_to.except(:where))
+ return narrowed if scoped_to.where_clause.empty?
+ narrowed.where(scoped_to.where_clause.ast)
+ end
+
+ def page(requested) = requested
+
+ def pairing_keys = []
+
+ private
+
+ attr_reader :scoped_to
+ end
+end
diff --git a/lib/json_api_kit/sideload.rb b/lib/json_api_kit/sideload.rb
new file mode 100644
index 00000000000..42a126ad983
--- /dev/null
+++ b/lib/json_api_kit/sideload.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Sideload
+ delegate :name, to: :relationship
+
+ def initialize(relationship, paths:, rows:, request:, schema:)
+ @relationship = relationship
+ @paths = paths
+ @rows = rows
+ @request = request
+ @schema = schema
+ end
+
+ def linkage_for(row) = relationship.linkage(related_to(row))
+
+ private
+
+ attr_reader :relationship, :paths, :rows, :request, :schema
+
+ def records = related_listing.records
+
+ def related_listing
+ @related_listing ||=
+ relationship.listing(
+ request.for_sideload(paths),
+ guardian: request.guardian,
+ scoped_to: relationship.scoping(association),
+ )
+ end
+
+ def related_to(row) = related_by_row.fetch(row.record, Records.new([]))
+
+ def related_by_row
+ @related_by_row ||=
+ association.pair(records.map(&:record)).transform_values { records.fetch_all(it) }
+ end
+
+ def owner_records = rows.map(&:record)
+
+ def association = @association ||= schema.association(name.to_sym, owner_records)
+ end
+end
diff --git a/lib/json_api_kit/sideloads.rb b/lib/json_api_kit/sideloads.rb
new file mode 100644
index 00000000000..31fb2765665
--- /dev/null
+++ b/lib/json_api_kit/sideloads.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Sideloads
+ def self.for(relationships, paths:, rows:, request:, schema:)
+ new(
+ relationships.map do
+ Sideload.new(it, paths: paths.next_for(it.name), rows:, request:, schema:)
+ end,
+ )
+ end
+
+ def initialize(sideloads)
+ @sideloads = sideloads
+ end
+
+ def linkage_for(row) = sideloads.to_h { [it.name, it.linkage_for(row)] }
+
+ private
+
+ attr_reader :sideloads
+ end
+end
diff --git a/lib/json_api_kit/url.rb b/lib/json_api_kit/url.rb
new file mode 100644
index 00000000000..c9598ae31e3
--- /dev/null
+++ b/lib/json_api_kit/url.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Url
+ PAGE = "page"
+
+ ENDS = %w[after before].freeze
+ WINDOW = %w[anchor before_size after_size include_anchor].freeze
+
+ def initialize(address, parameters = {})
+ @address = address
+ @parameters = parameters
+ end
+
+ def at(**page)
+ self.class.new(
+ address,
+ parameters.merge(
+ PAGE => page_parameters.except(*ENDS, *WINDOW).merge(page.transform_keys(&:to_s)),
+ ),
+ )
+ end
+
+ def to_s = "#{address}#{query_string}"
+
+ private
+
+ attr_reader :address, :parameters
+
+ def page_parameters = parameters.fetch(PAGE, {})
+
+ def query_string = parameters.to_query.presence&.then { "?#{it}" }
+ end
+end
diff --git a/lib/json_api_kit/urls.rb b/lib/json_api_kit/urls.rb
new file mode 100644
index 00000000000..968a7c36b8f
--- /dev/null
+++ b/lib/json_api_kit/urls.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Urls
+ def initialize(base:, current:, parameters: {})
+ @base = base
+ @current = current
+ @parameters = parameters
+ end
+
+ def current = Url.new(@current, parameters)
+
+ def record(type, id) = Url.new("#{base}/#{type}/#{id}")
+
+ def relationship(type, id, name) = Url.new("#{record(type, id)}/relationships/#{name}")
+
+ def related(type, id, name) = Url.new("#{record(type, id)}/#{name}")
+
+ private
+
+ attr_reader :base, :parameters
+ end
+end
diff --git a/spec/integration/json_api_kit/anchors_spec.rb b/spec/integration/json_api_kit/anchors_spec.rb
new file mode 100644
index 00000000000..fbf208a4b00
--- /dev/null
+++ b/spec/integration/json_api_kit/anchors_spec.rb
@@ -0,0 +1,376 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a listing entered at an anchor" do
+ include_context "with a listing of topics"
+
+ fab!(:earliest) do
+ Fabricate(:topic, title: "Before everything else", created_at: Time.utc(2026, 7, 31))
+ end
+ fab!(:latest) do
+ Fabricate(:topic, title: "After everything else", created_at: Time.utc(2026, 8, 4))
+ end
+
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ before_size: 1,
+ after_size: 1,
+ },
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ it "returns a page centred on the anchor row" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ ],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(oldest, sort: { created_at: :asc })),
+ next: page_url(after: cursor_of_record(newest, sort: { created_at: :asc })),
+ ),
+ )
+ end
+
+ context "when the page has a size alone" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ size: 2,
+ },
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ it "returns that many rows from the anchor row" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title]), topic_object(newest, fields: %w[title])],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle, sort: { created_at: :asc })),
+ next: page_url(after: cursor_of_record(newest, sort: { created_at: :asc })),
+ ),
+ )
+ end
+ end
+
+ context "when the anchor is a value of the sort" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ created_at: Time.utc(2026, 8, 2),
+ },
+ size: 2,
+ },
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ it "starts at the row holding that value" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title]), topic_object(newest, fields: %w[title])],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle, sort: { created_at: :asc })),
+ next: page_url(after: cursor_of_record(newest, sort: { created_at: :asc })),
+ ),
+ )
+ end
+ end
+
+ context "when no row holds the anchor value" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ created_at: Time.utc(2026, 8, 1, 12),
+ },
+ size: 2,
+ },
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ it "starts at the first row past it" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title]), topic_object(newest, fields: %w[title])],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle, sort: { created_at: :asc })),
+ next: page_url(after: cursor_of_record(newest, sort: { created_at: :asc })),
+ ),
+ )
+ end
+ end
+
+ context "when the anchor value is past every row holding one" do
+ fab!(:never_posted) do
+ Fabricate(:topic, title: "Nothing has been posted here", last_posted_at: nil)
+ end
+
+ let(:params) do
+ {
+ sort: {
+ last_posted_at: :asc,
+ },
+ page: {
+ anchor: {
+ last_posted_at: Time.utc(2030, 1, 1),
+ },
+ size: 1,
+ },
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ before do
+ [earliest, oldest, middle, newest, latest].each do |topic|
+ topic.update_columns(last_posted_at: topic.created_at)
+ end
+ end
+
+ it "starts at the first row holding none" do
+ expect(document).to eq(
+ data: [topic_object(never_posted, fields: %w[title])],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(never_posted, sort: { last_posted_at: :asc })),
+ ),
+ )
+ end
+
+ context "when every row holds one" do
+ before { never_posted.update_columns(last_posted_at: Time.utc(2026, 8, 6)) }
+
+ it "returns no row" do
+ expect(listed_ids).to be_empty
+ end
+ end
+
+ context "when the nulls read first" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ sort :last_posted_at, nulls: :first
+ default_sort last_posted_at: :asc
+ anchor :last_posted_at
+ end
+ end
+
+ it "returns no row" do
+ expect(listed_ids).to be_empty
+ end
+
+ context "when every row holds one" do
+ before { never_posted.update_columns(last_posted_at: Time.utc(2026, 8, 6)) }
+
+ it "returns no row" do
+ expect(listed_ids).to be_empty
+ end
+ end
+ end
+ end
+
+ context "when the server calculates the anchor" do
+ let(:guardian) { Guardian.new(middle.user) }
+ let(:params) do
+ { sort: { created_at: :asc }, page: { anchor: :mine, size: 1 }, fields: { topics: [:title] } }
+ end
+
+ it "starts at the row it finds for the current user" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title])],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle, sort: { created_at: :asc })),
+ next: page_url(after: cursor_of_record(middle, sort: { created_at: :asc })),
+ ),
+ )
+ end
+
+ context "when the calculated anchor holds no row" do
+ let(:guardian) { Guardian.new }
+
+ it "starts at the first row of the listing" do
+ expect(document).to eq(
+ data: [topic_object(earliest, fields: %w[title])],
+ included: [],
+ links:
+ links_of(next: page_url(after: cursor_of_record(earliest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+ end
+
+ context "when the anchor is an id no row holds" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { id: -1 } } } }
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No row for the anchor",
+ detail: "No record has id -1.",
+ parameter: "page[anchor][id]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the anchor is on another sort" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { title: middle.title } } } }
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Anchor does not match the sort",
+ detail: "The anchor is title, but this request sorts by created_at.",
+ parameter: "page[anchor][title]",
+ ),
+ ],
+ )
+ end
+ end
+
+ describe "the window either side of the anchor" do
+ context "when the window is larger than the maximum" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ before_size: 3_000,
+ after_size: 3_000,
+ },
+ }
+ end
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window is too large",
+ detail: "A window of 6001 rows exceeds the maximum of 100.",
+ parameter: "page[before_size]",
+ links: {
+ type: profile_link("max-size-exceeded"),
+ },
+ meta: {
+ page: {
+ maxSize: 100,
+ },
+ },
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the window is empty" do
+ let(:params) do
+ {
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ before_size: 0,
+ after_size: 0,
+ include_anchor: false,
+ },
+ }
+ end
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window is empty",
+ detail: "A window must be at least 1 row.",
+ parameter: "page[before_size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a side of the window is negative" do
+ let(:params) { { page: { anchor: { id: middle.id }, before_size: -1, after_size: 2 } } }
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window size is negative",
+ detail: "page[before_size] must be 0 or greater.",
+ parameter: "page[before_size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a side of the window is not an integer" do
+ let(:params) { { page: { anchor: { id: middle.id }, after_size: "two" } } }
+
+ it "renders the error as a document" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window size is not an integer",
+ detail: "page[after_size] must be an integer.",
+ parameter: "page[after_size]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/cursors_spec.rb b/spec/integration/json_api_kit/cursors_spec.rb
new file mode 100644
index 00000000000..945df1a7dfd
--- /dev/null
+++ b/spec/integration/json_api_kit/cursors_spec.rb
@@ -0,0 +1,198 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a listing read from a cursor" do
+ include_context "with a listing of topics"
+
+ let(:sort) { { created_at: :asc } }
+ let(:cursor) { cursor_for(middle) }
+ let(:sorted_listing) { listing_of({ sort:, page: { item_cursors: true } }) }
+
+ describe "the cursor of a row" do
+ it "is left out unless the request asks for it" do
+ expect(listing_of({ sort: })[:data]).to all(exclude(:meta))
+ end
+
+ it "is sent when the request asks for it" do
+ expect(sorted_listing[:data].map { it[:meta][:page][:cursor] }).to all(be_present)
+ end
+ end
+ let(:pages) do
+ sorted_listing[:data].map do
+ listing_of({ sort:, page: { after: cursor_of(it) }, fields: { topics: [:title] } })
+ end
+ end
+
+ def cursor_for(record) = cursor_of(sorted_listing[:data].detect { it[:id] == record.id.to_s })
+
+ it "reads a page from the cursor of every row" do
+ expect(pages).to eq(
+ [
+ {
+ data: [topic_object(middle, fields: %w[title]), topic_object(newest, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(middle))),
+ },
+ {
+ data: [topic_object(newest, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(newest))),
+ },
+ { data: [], included: [], links: links_of(prev: page_url(before: cursor_for(newest))) },
+ ],
+ )
+ end
+
+ context "when the request holds page[after]" do
+ let(:params) { { sort:, page: { after: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the rows after the cursor" do
+ expect(document).to eq(
+ data: [topic_object(newest, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(newest))),
+ )
+ end
+ end
+
+ context "when the request holds page[before]" do
+ let(:params) { { sort:, page: { before: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the rows before the cursor" do
+ expect(document).to eq(
+ data: [topic_object(oldest, fields: %w[title])],
+ included: [],
+ links: links_of(next: page_url(after: cursor_for(oldest))),
+ )
+ end
+ end
+
+ context "when the sort is created_at desc" do
+ let(:sort) { { created_at: :desc } }
+ let(:params) { { sort:, page: { after: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the rows after the cursor" do
+ expect(document).to eq(
+ data: [topic_object(oldest, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(oldest))),
+ )
+ end
+ end
+
+ context "when the cursor comes from a backwards page" do
+ let(:cursor) do
+ cursor_at(0, listing_of({ sort:, page: { before: super(), item_cursors: true } }))
+ end
+ let(:params) { { sort:, page: { after: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the rows after the cursor" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title]), topic_object(newest, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(middle))),
+ )
+ end
+ end
+
+ context "when the cursor comes from the last row" do
+ let(:cursor) { cursor_for(newest) }
+ let(:params) { { sort:, page: { after: cursor }, fields: { topics: [:title] } } }
+
+ it "returns no row and links to no next page" do
+ expect(document).to eq(
+ data: [],
+ included: [],
+ links: links_of(prev: page_url(before: cursor)),
+ )
+ end
+ end
+
+ context "when the sort is last_posted_at and one row holds none" do
+ fab!(:never_posted) do
+ Fabricate(:topic, title: "Nothing has been posted here", last_posted_at: nil)
+ end
+
+ before { [oldest, middle, newest].each { it.update_columns(last_posted_at: it.created_at) } }
+
+ let(:sort) { { last_posted_at: :asc } }
+
+ context "when the cursor comes from the last row holding a value" do
+ let(:cursor) { cursor_for(newest) }
+ let(:params) { { sort:, page: { after: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the row holding no value" do
+ expect(document).to eq(
+ data: [topic_object(never_posted, fields: %w[title])],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_for(never_posted))),
+ )
+ end
+ end
+
+ context "when the cursor comes from the row holding no value" do
+ let(:cursor) { cursor_for(never_posted) }
+ let(:params) { { sort:, page: { before: cursor }, fields: { topics: [:title] } } }
+
+ it "returns the rows holding a value" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of(next: page_url(after: cursor_for(newest))),
+ )
+ end
+ end
+
+ context "when the request sorts by created_at" do
+ let(:cursor) { cursor_for(never_posted) }
+ let(:params) do
+ { sort: { created_at: :asc }, page: { after: cursor }, fields: { topics: [:title] } }
+ end
+
+ it "refuses the cursor" do
+ expect(rendered_error).to eq(
+ refusal(
+ title: "Invalid cursor",
+ detail: "Use a cursor from this resource and this sort.",
+ parameter: "page[after]",
+ ),
+ )
+ end
+ end
+ end
+
+ context "when the cursor comes from another sort of the same shape" do
+ let(:cursor) { cursor_of_record(middle, sort: { title: :asc }) }
+ let(:params) { { sort: { created_at: :asc }, page: { after: cursor } } }
+
+ it "refuses the cursor" do
+ expect(rendered_error).to eq(
+ refusal(
+ title: "Invalid cursor",
+ detail: "Use a cursor from this resource and this sort.",
+ parameter: "page[after]",
+ ),
+ )
+ end
+ end
+
+ context "when the cursor comes from another resource" do
+ let(:cursor) { cursor_of_record(middle.user, of: JsonApiKitSpec::UserResource) }
+ let(:params) { { page: { after: cursor } } }
+
+ it "refuses the cursor" do
+ expect(rendered_error).to eq(
+ refusal(
+ title: "Invalid cursor",
+ detail: "Use a cursor from this resource and this sort.",
+ parameter: "page[after]",
+ ),
+ )
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/documents_spec.rb b/spec/integration/json_api_kit/documents_spec.rb
new file mode 100644
index 00000000000..12d79808ea2
--- /dev/null
+++ b/spec/integration/json_api_kit/documents_spec.rb
@@ -0,0 +1,177 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a rendered document" do
+ include_context "with a listing of topics"
+
+ describe "a listing" do
+ let(:params) { { sort: { created_at: :asc }, page: { size: 1 } } }
+ let(:query) { { "page" => { "size" => "1" } } }
+
+ it "renders the first page of the listing" do
+ expect(document).to eq(
+ data: [topic_object(oldest)],
+ included: [],
+ links: links_of(next: page_url(after: cursor_of_record(oldest), size: 1)),
+ )
+ end
+
+ context "when all parameters are strings" do
+ let(:params) do
+ { "sort" => { "created_at" => "asc" }, "fields" => { "topics" => %w[title] } }
+ end
+ let(:query) { {} }
+
+ it "renders the same listing" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the page holds the last row of the listing" do
+ let(:params) { { sort: { created_at: :asc }, page: { size: 5 } } }
+ let(:query) { { "page" => { "size" => "5" } } }
+
+ it "links to no page after it" do
+ expect(document).to eq(
+ data: [topic_object(oldest), topic_object(middle), topic_object(newest)],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the page follows another page" do
+ let(:params) do
+ { sort: { created_at: :asc }, page: { size: 1, after: cursor_of_record(oldest) } }
+ end
+ let(:query) { { "page" => { "size" => "1", "after" => cursor_of_record(oldest) } } }
+
+ it "links to the page before it" do
+ expect(document).to eq(
+ data: [topic_object(middle)],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle), size: 1),
+ next: page_url(after: cursor_of_record(middle), size: 1),
+ ),
+ )
+ end
+ end
+
+ context "when the listing holds no row" do
+ let(:params) do
+ { sort: { created_at: :asc }, filter: { title: "No topic carries this title" } }
+ end
+ let(:query) { {} }
+
+ it "renders an empty list" do
+ expect(document).to eq(data: [], included: [], links: links_of)
+ end
+ end
+ end
+
+ describe "one record" do
+ let(:current) { "https://example.com/api/topics/#{middle.id}" }
+
+ it "renders the record" do
+ expect(one_document(middle.id)).to eq(
+ data: topic_object(middle),
+ included: [],
+ links: {
+ self: self_link,
+ },
+ )
+ end
+
+ context "when the request asks for one field" do
+ let(:params) { { fields: { topics: [:title] } } }
+
+ it "renders that field only" do
+ expect(one_document(middle.id)).to eq(
+ data: topic_object(middle, fields: %w[title]),
+ included: [],
+ links: {
+ self: self_link,
+ },
+ )
+ end
+ end
+
+ context "when the request includes a relationship" do
+ let(:params) { { include: %w[user] } }
+ let(:query) { { "include" => "user" } }
+
+ it "links to itself with the parameters of the request" do
+ expect(one_document(middle.id)[:links]).to eq(self: self_link)
+ end
+ end
+
+ context "when no record has that id" do
+ it "renders a not found error" do
+ expect(rendered_error(one_document(-1))).to eq(not_found)
+ end
+ end
+
+ context "when the resource does not expose the row" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ scope { |guardian| Topic.where(closed: true) }
+ end
+ end
+
+ it "renders a not found error" do
+ expect(rendered_error(one_document(middle.id))).to eq(not_found)
+ end
+ end
+ end
+
+ describe "the parameters a caller sends" do
+ let(:params) { { "page" => { "anchor" => { "id" => middle.id }, "size" => 1 } } }
+
+ it "stay as they were" do
+ expect { document }.not_to change { params.deep_dup }
+ end
+ end
+
+ describe "the status of a document" do
+ subject(:status) do
+ JsonApiKit::Document::Collection.for(params, resource:, guardian:, urls:).status
+ end
+
+ it "answers 200 for a rendered listing" do
+ expect(status).to eq("200")
+ end
+
+ context "when the document holds one record" do
+ subject(:status) do
+ JsonApiKit::Document::Individual.for(middle.id, params, resource:, guardian:, urls:).status
+ end
+
+ it "answers 200 for a rendered record" do
+ expect(status).to eq("200")
+ end
+ end
+
+ context "when no record has that id" do
+ subject(:status) do
+ JsonApiKit::Document::Individual.for(-1, params, resource:, guardian:, urls:).status
+ end
+
+ it "answers 404 for a not found error" do
+ expect(status).to eq("404")
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/errors_spec.rb b/spec/integration/json_api_kit/errors_spec.rb
new file mode 100644
index 00000000000..ce4dab82b4e
--- /dev/null
+++ b/spec/integration/json_api_kit/errors_spec.rb
@@ -0,0 +1,666 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a refused request" do
+ include_context "with a listing of topics"
+
+ let(:cursor) { cursor_of_record(middle) }
+
+ describe "the sort parameter" do
+ context "when the sort is a string" do
+ let(:params) { { sort: "created_at" } }
+
+ it "refuses the sort" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid sort parameter",
+ detail: "sort must name a direction for each sort.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the resource declares no such sort" do
+ let(:params) { { sort: { secrets: :asc } } }
+
+ it "refuses the sort" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such sort",
+ detail: "There is no sort named secrets.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+
+ it "answers the status 400" do
+ expect(
+ JsonApiKit::Document::Collection.for(params, resource:, guardian:, urls:).status,
+ ).to eq("400")
+ end
+ end
+
+ context "when the sort direction is neither asc nor desc" do
+ let(:params) { { sort: { created_at: :sideways } } }
+
+ it "refuses the sort" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such sort direction",
+ detail: "Sort direction sideways is not asc or desc.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when an undeclared sort comes with an anchor" do
+ let(:params) { { sort: { secrets: :asc }, page: { anchor: { title: middle.title } } } }
+
+ it "refuses the sort alone" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such sort",
+ detail: "There is no sort named secrets.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when an undeclared sort comes with a cursor" do
+ let(:params) { { sort: { secrets: :asc }, page: { after: cursor } } }
+
+ it "refuses the sort alone" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such sort",
+ detail: "There is no sort named secrets.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a request for one record has a sort" do
+ let(:params) { { sort: { created_at: :asc } } }
+
+ it "refuses the sort" do
+ expect(one_document(middle.id)).to eq(
+ errors: [
+ refusal(
+ title: "No such parameter",
+ detail: "There is no parameter named sort.",
+ parameter: "sort",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "the filter parameter" do
+ context "when the filter is a string" do
+ let(:params) { { filter: "title" } }
+
+ it "refuses the filter" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid filter parameter",
+ detail: "filter must name a value for each filter.",
+ parameter: "filter",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the resource declares no such filter" do
+ let(:params) { { filter: { secrets: "hidden" } } }
+
+ it "refuses the filter" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such filter",
+ detail: "There is no filter named secrets.",
+ parameter: "filter[secrets]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the filter value is an empty set" do
+ let(:params) { { filter: { title: {} } } }
+
+ it "refuses the filter value" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid filter value",
+ detail: "filter[title] must be a value or a list of values.",
+ parameter: "filter[title]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the filter value is a set of values" do
+ let(:params) { { filter: { title: { like: "a topic" } } } }
+
+ it "refuses the filter value" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid filter value",
+ detail: "filter[title] must be a value or a list of values.",
+ parameter: "filter[title]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "the fields parameter" do
+ context "when the fields are a string" do
+ let(:params) { { fields: "title" } }
+
+ it "refuses the fields" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid fields parameter",
+ detail: "fields must name a list of fields for each type.",
+ parameter: "fields",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the fieldset of a type is a string" do
+ let(:params) { { fields: { topics: "title" } } }
+
+ it "refuses the fieldset" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid fields value",
+ detail: "fields[topics] must be a list of field names.",
+ parameter: "fields[topics]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "the include parameter" do
+ context "when the resource declares no such path" do
+ let(:params) { { include: %w[secrets] } }
+
+ it "refuses the path" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such relationship path",
+ detail: "There is no relationship path named secrets.",
+ parameter: "include",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "an unknown parameter" do
+ context "when the parameter is at the top level" do
+ let(:params) { { sorts: { created_at: :asc } } }
+
+ it "refuses the parameter" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such parameter",
+ detail: "There is no parameter named sorts.",
+ parameter: "sorts",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the parameter is under page" do
+ let(:params) { { page: { sise: 2 } } }
+
+ it "refuses the parameter" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such parameter",
+ detail: "There is no parameter named page[sise].",
+ parameter: "page[sise]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "the page parameter" do
+ context "when the page is a string" do
+ let(:params) { { page: "big" } }
+
+ it "refuses the page" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid page parameter",
+ detail: "page must name page parameters, as in page[size]=2.",
+ parameter: "page",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the page size is not a number" do
+ let(:params) { { page: { size: "two" } } }
+
+ it "refuses the page size" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Page size is not an integer",
+ detail: "Page size must be an integer.",
+ parameter: "page[size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the page size is 0" do
+ let(:params) { { page: { size: 0 } } }
+
+ it "refuses the page size" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Page size is too small",
+ detail: "Page size must be at least 1.",
+ parameter: "page[size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the page size is above the maximum" do
+ let(:params) { { page: { size: 5_000 } } }
+
+ it "refuses the page size" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Page size is too large",
+ detail: "Page size 5000 exceeds the maximum of 100.",
+ parameter: "page[size]",
+ links: {
+ type: profile_link("max-size-exceeded"),
+ },
+ meta: {
+ page: {
+ maxSize: 100,
+ },
+ },
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the cursor is not base64" do
+ let(:params) { { page: { after: "not-a-cursor" } } }
+
+ it "refuses the cursor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid cursor",
+ detail: "Use a cursor from this resource and this sort.",
+ parameter: "page[after]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the cursor comes from another sort" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ after: cursor_of_record(middle, sort: { title: :asc }),
+ },
+ }
+ end
+
+ it "refuses the cursor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid cursor",
+ detail: "Use a cursor from this resource and this sort.",
+ parameter: "page[after]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a cursor is at both ends of the page" do
+ let(:params) { { page: { after: cursor, before: cursor } } }
+
+ it "refuses both parameters" do
+ expect(document).to eq(
+ errors:
+ %w[page[after] page[before]].map do
+ refusal(
+ title: "Range pagination is not supported",
+ detail: "Use page[after] or page[before], not both.",
+ parameter: it,
+ links: {
+ type: profile_link("range-pagination-not-supported"),
+ },
+ )
+ end,
+ )
+ end
+ end
+ end
+
+ describe "the window parameters" do
+ context "when the request has no anchor" do
+ let(:params) { { page: { before_size: 2, after_size: 2 } } }
+
+ it "refuses the window" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Anchor is required",
+ detail: "page[before_size], page[after_size] need an anchor.",
+ parameter: "page[anchor]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the window is above the maximum" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ before_size: 3_000,
+ after_size: 3_000,
+ },
+ }
+ end
+
+ it "refuses the window" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window is too large",
+ detail: "A window of 6001 rows exceeds the maximum of 100.",
+ parameter: "page[before_size]",
+ links: {
+ type: profile_link("max-size-exceeded"),
+ },
+ meta: {
+ page: {
+ maxSize: 100,
+ },
+ },
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the window is empty" do
+ let(:params) do
+ {
+ page: {
+ anchor: {
+ id: middle.id,
+ },
+ before_size: 0,
+ after_size: 0,
+ include_anchor: false,
+ },
+ }
+ end
+
+ it "refuses the window" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window is empty",
+ detail: "A window must be at least 1 row.",
+ parameter: "page[before_size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a side of the window is negative" do
+ let(:params) { { page: { anchor: { id: middle.id }, before_size: -1, after_size: 2 } } }
+
+ it "refuses the window" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window size is negative",
+ detail: "page[before_size] must be 0 or greater.",
+ parameter: "page[before_size]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when a side of the window is not a number" do
+ let(:params) { { page: { anchor: { id: middle.id }, after_size: "two" } } }
+
+ it "refuses the window" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Window size is not an integer",
+ detail: "page[after_size] must be an integer.",
+ parameter: "page[after_size]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "the anchor parameter" do
+ context "when the resource declares no such anchor" do
+ let(:params) { { page: { anchor: { views: 1 } } } }
+
+ it "refuses the anchor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No such anchor",
+ detail: "There is no anchor named views.",
+ parameter: "page[anchor][views]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the request has two anchors" do
+ let(:params) { { page: { anchor: { id: 1, title: "a topic" } } } }
+
+ it "refuses the anchor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Too many anchors",
+ detail: "Use one anchor only. This request has 2.",
+ parameter: "page[anchor]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the anchor value is a list" do
+ let(:params) { { page: { anchor: { id: [1, 2] } } } }
+
+ it "refuses the anchor value" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Invalid anchor value",
+ detail: "page[anchor][id] must be a single value.",
+ parameter: "page[anchor][id]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the anchor value is not a number" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { id: "not a number" } } } }
+
+ it "refuses the anchor value" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No row for the anchor",
+ detail: "No record has id \"not a number\".",
+ parameter: "page[anchor][id]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when no row has the anchor id" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { id: -1 } } } }
+
+ it "refuses the anchor value" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "No row for the anchor",
+ detail: "No record has id -1.",
+ parameter: "page[anchor][id]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the anchor is not the sort" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { title: middle.title } } } }
+
+ it "refuses the anchor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Anchor does not match the sort",
+ detail: "The anchor is title, but this request sorts by created_at.",
+ parameter: "page[anchor][title]",
+ ),
+ ],
+ )
+ end
+ end
+
+ context "when the request has an anchor and a cursor" do
+ let(:params) { { page: { anchor: { id: oldest.id }, after: cursor } } }
+
+ it "refuses the anchor" do
+ expect(document).to eq(
+ errors: [
+ refusal(
+ title: "Anchor and cursor cannot be combined",
+ detail: "Use page[anchor] or page[after], not both.",
+ parameter: "page[anchor]",
+ ),
+ ],
+ )
+ end
+ end
+ end
+
+ describe "a refusal a caller never sees" do
+ context "when a related resource sorts by a column that can be null" do
+ let(:resource) do
+ related =
+ Class.new(JsonApiKit::Resource) do
+ model Post
+ type :posts
+ attribute :post_number
+ sort :edited_at, column: :last_editor_edited_at, nulls: :last
+ default_sort edited_at: :desc
+ end
+
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ has_many :posts, resource: related
+ end
+ end
+ let(:params) { { include: %w[posts] } }
+
+ it "raises a split order error" do
+ expect { document }.to raise_error(
+ JsonApiKit::Pagination::PagePerOwner::SplitOrder,
+ /edited_at/,
+ )
+ end
+ end
+
+ context "when the anchor is not the sort" do
+ let(:params) { { sort: { created_at: :asc }, page: { anchor: { title: middle.title } } } }
+
+ it "raises on a direct read" do
+ expect { resource.all(params, guardian:).records }.to raise_error(ArgumentError, /title/)
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/filtering_spec.rb b/spec/integration/json_api_kit/filtering_spec.rb
new file mode 100644
index 00000000000..675925c81cf
--- /dev/null
+++ b/spec/integration/json_api_kit/filtering_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a filtered listing" do
+ include_context "with a listing of topics"
+
+ let(:params) { { filter: { title: middle.title } } }
+
+ it "keeps the rows the filter allows" do
+ expect(document).to eq(data: [topic_object(middle)], included: [], links: links_of)
+ end
+
+ context "when the filter keeps no row" do
+ let(:params) { { filter: { title: "No topic carries this title" } } }
+
+ it "returns an empty listing" do
+ expect(document).to eq(data: [], included: [], links: links_of)
+ end
+ end
+
+ context "when the filter value is a list" do
+ let(:params) { { sort: { created_at: :asc }, filter: { title: [oldest.title, newest.title] } } }
+
+ it "keeps a row for each value of the list" do
+ expect(document).to eq(
+ data: [topic_object(oldest), topic_object(newest)],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/pagination_spec.rb b/spec/integration/json_api_kit/pagination_spec.rb
new file mode 100644
index 00000000000..271f763f379
--- /dev/null
+++ b/spec/integration/json_api_kit/pagination_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a page of a listing" do
+ include_context "with a listing of topics"
+
+ let(:params) { { sort: { created_at: :asc }, page: { size: 2 } } }
+ let(:query) { { "page" => { "size" => "2" } } }
+
+ it "returns the first page and links to the next" do
+ expect(document).to eq(
+ data: [topic_object(oldest), topic_object(middle)],
+ included: [],
+ links:
+ links_of(
+ next: page_url(after: cursor_of_record(middle, sort: { created_at: :asc }), size: 2),
+ ),
+ )
+ end
+
+ context "when the page size holds the whole listing" do
+ let(:params) { { sort: { created_at: :asc }, page: { size: 5 } } }
+ let(:query) { { "page" => { "size" => "5" } } }
+
+ it "returns every row and links to no other page" do
+ expect(document).to eq(
+ data: [topic_object(oldest), topic_object(middle), topic_object(newest)],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the request holds no page size" do
+ fab!(:replies) { 3.times.map { Fabricate(:post, topic: oldest) } }
+
+ let(:resource) { JsonApiKitSpec::PostResource }
+ let(:current) { "https://example.com/api/posts" }
+ let(:params) { {} }
+ let(:query) { {} }
+
+ it "returns as many rows as the resource declares" do
+ expect(document).to eq(
+ data: [post_object(replies.first), post_object(replies.second)],
+ included: [],
+ links: links_of(next: page_url(after: cursor_of_record(replies.second))),
+ )
+ end
+ end
+
+ context "when the page follows the first page" do
+ let(:cursor) { cursor_of_record(oldest, sort: { created_at: :asc }) }
+ let(:params) { { sort: { created_at: :asc }, page: { size: 1, after: cursor } } }
+ let(:query) { { "page" => { "size" => "1", "after" => cursor } } }
+
+ it "returns the page and links either side of it" do
+ expect(document).to eq(
+ data: [topic_object(middle)],
+ included: [],
+ links:
+ links_of(
+ prev: page_url(before: cursor_of_record(middle, sort: { created_at: :asc }), size: 1),
+ next: page_url(after: cursor_of_record(middle, sort: { created_at: :asc }), size: 1),
+ ),
+ )
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/relationships_spec.rb b/spec/integration/json_api_kit/relationships_spec.rb
new file mode 100644
index 00000000000..cd975e79176
--- /dev/null
+++ b/spec/integration/json_api_kit/relationships_spec.rb
@@ -0,0 +1,521 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a document with related records" do
+ include_context "with a listing of topics"
+
+ fab!(:author) { Fabricate(:user, username: "the_author") }
+ fab!(:group) { Fabricate(:group, name: "everyone_who_writes").tap { it.add(author) } }
+ fab!(:category) { Fabricate(:category, name: "Where the topic sits") }
+ fab!(:tag) { Fabricate(:tag, name: "a-tag-it-carries") }
+ fab!(:topic) do
+ Fabricate(
+ :topic,
+ user: author,
+ category:,
+ title: "A topic that has relations",
+ created_at: Time.utc(2026, 8, 4),
+ )
+ end
+ fab!(:tagging) { Fabricate(:topic_tag, topic:, tag:) }
+
+ let(:scoped_to) { Topic.where(id: topic.id) }
+ let(:params) { { include: %w[user] } }
+
+ describe "a relationship to one record" do
+ it "renders the row and its related record" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ },
+ ),
+ ],
+ included: [user_object(author)],
+ links: links_of,
+ )
+ end
+
+ context "when the page holds more rows than the related resource's default page" do
+ fab!(:topics_by_many_users) do
+ Array.new(JsonApiKit::Page::Limits::DEFAULT + 1) do
+ Fabricate(:topic, user: Fabricate(:user))
+ end
+ end
+
+ let(:scoped_to) { Topic.where(id: topics_by_many_users) }
+ let(:params) { { include: %w[user], page: { size: topics_by_many_users.size } } }
+
+ it "renders a related record for every row" do
+ expect(document[:included].map { it[:id] }).to match_array(
+ topics_by_many_users.map { it.user_id.to_s },
+ )
+ end
+ end
+ end
+
+ context "when the request asks for no relationship" do
+ let(:params) { {} }
+
+ it "renders no relationship and no related record" do
+ expect(document).to eq(data: [topic_object(topic)], included: [], links: links_of)
+ end
+ end
+
+ context "when the relationship holds no record" do
+ fab!(:bare) do
+ Fabricate(
+ :private_message_topic,
+ title: "A topic in no category at all",
+ created_at: Time.utc(2026, 8, 6),
+ )
+ end
+
+ let(:scoped_to) { Topic.where(id: bare.id) }
+ let(:params) { { include: %w[category] } }
+
+ it "links the row to no record" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ bare,
+ relationships: {
+ "category" => relationship_object("topics", bare, "category", data: nil),
+ },
+ ),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ describe "a relationship to many records" do
+ let(:params) { { include: %w[tags] } }
+
+ it "renders the row and every related record" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "tags" =>
+ paged_relationship_object(
+ "topics",
+ topic,
+ "tags",
+ data: [identifier_of("tags", tag)],
+ ),
+ },
+ ),
+ ],
+ included: [tag_object(tag)],
+ links: links_of,
+ )
+ end
+
+ context "when the relationship holds no record" do
+ let(:scoped_to) { Topic.where(id: oldest.id) }
+
+ it "links the row to an empty list" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ oldest,
+ relationships: {
+ "tags" => paged_relationship_object("topics", oldest, "tags", data: []),
+ },
+ ),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+ end
+
+ describe "a path through one relationship" do
+ let(:params) { { include: %w[user.groups] } }
+
+ it "renders every record of the path" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ },
+ ),
+ ],
+ included: [
+ user_object(
+ author,
+ relationships: {
+ "groups" =>
+ paged_relationship_object(
+ "users",
+ author,
+ "groups",
+ data: [identifier_of("groups", group)],
+ ),
+ },
+ ),
+ group_object(group),
+ ],
+ links: links_of,
+ )
+ end
+ end
+
+ describe "a path through three relationships" do
+ let(:params) { { include: %w[user.groups.users] } }
+
+ it "renders every record of the path one time" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ },
+ ),
+ ],
+ included: [
+ user_object(
+ author,
+ relationships: {
+ "groups" =>
+ paged_relationship_object(
+ "users",
+ author,
+ "groups",
+ data: [identifier_of("groups", group)],
+ ),
+ },
+ ),
+ group_object(
+ group,
+ relationships: {
+ "users" =>
+ paged_relationship_object(
+ "groups",
+ group,
+ "users",
+ data: [identifier_of("users", author)],
+ ),
+ },
+ ),
+ ],
+ links: links_of,
+ )
+ end
+ end
+
+ describe "a record two rows reach" do
+ fab!(:another) do
+ Fabricate(
+ :topic,
+ user: author,
+ title: "Another topic by the same author",
+ created_at: Time.utc(2026, 8, 5),
+ )
+ end
+
+ let(:scoped_to) { Topic.where(id: [topic.id, another.id]) }
+
+ it "renders it one time for both rows" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ another,
+ relationships: {
+ "user" =>
+ relationship_object(
+ "topics",
+ another,
+ "user",
+ data: identifier_of("users", author),
+ ),
+ },
+ ),
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ },
+ ),
+ ],
+ included: [user_object(author)],
+ links: links_of,
+ )
+ end
+ end
+
+ describe "a record two paths reach" do
+ fab!(:post) { Fabricate(:post, topic:, user: author) }
+
+ let(:params) { { include: %w[user posts.user.groups] } }
+
+ it "renders it one time with its relationships" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ "posts" =>
+ paged_relationship_object(
+ "topics",
+ topic,
+ "posts",
+ data: [identifier_of("posts", post)],
+ ),
+ },
+ ),
+ ],
+ included: [
+ user_object(
+ author,
+ relationships: {
+ "groups" =>
+ paged_relationship_object(
+ "users",
+ author,
+ "groups",
+ data: [identifier_of("groups", group)],
+ ),
+ },
+ ),
+ post_object(
+ post,
+ relationships: {
+ "user" =>
+ relationship_object("posts", post, "user", data: identifier_of("users", author)),
+ },
+ ),
+ group_object(group),
+ ],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the path returns to the row it starts from" do
+ fab!(:post) { Fabricate(:post, topic:) }
+
+ let(:params) { { include: %w[posts.topic] } }
+
+ it "renders every record one time" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "posts" =>
+ paged_relationship_object(
+ "topics",
+ topic,
+ "posts",
+ data: [identifier_of("posts", post)],
+ ),
+ },
+ ),
+ ],
+ included: [
+ post_object(
+ post,
+ relationships: {
+ "topic" =>
+ relationship_object("posts", post, "topic", data: identifier_of("topics", topic)),
+ },
+ ),
+ ],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the scope of a related resource hides the record" do
+ let(:resource) do
+ staff =
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ scope { |guardian| User.where(admin: true) }
+ attribute :username
+ end
+
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ has_one :user, resource: staff
+ end
+ end
+
+ it "links the row to no record" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ fields: %w[title],
+ relationships: {
+ "user" => relationship_object("topics", topic, "user", data: nil),
+ },
+ ),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ describe "a page of rows" do
+ fab!(:another) { Fabricate(:topic, title: "One more topic alongside") }
+
+ let(:scoped_to) { Topic.where(id: [topic.id, another.id]) }
+
+ def reads_of_users(&block) = track_sql_queries(&block).grep(/FROM "users"/).size
+
+ it "reads the related records in one query" do
+ expect(reads_of_users { document }).to eq(1)
+ end
+
+ context "when the page is centred on an anchor" do
+ let(:params) do
+ { include: %w[user], page: { anchor: { id: topic.id }, before_size: 1, after_size: 1 } }
+ end
+
+ it "reads them in one query" do
+ expect(reads_of_users { document }).to eq(1)
+ end
+ end
+ end
+
+ describe "a relationship holding more records than one page" do
+ fab!(:posts) { 3.times.map { Fabricate(:post, topic:) } }
+
+ let(:params) { { include: %w[posts] } }
+
+ def next_page_of(row, post)
+ "#{base}/topics/#{row.id}/relationships/posts?" +
+ { page: { after: cursor_of_record(post, of: JsonApiKitSpec::PostResource) } }.to_query
+ end
+
+ it "renders one page of them and links to the next" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ topic,
+ relationships: {
+ "posts" =>
+ paged_relationship_object(
+ "topics",
+ topic,
+ "posts",
+ data: posts.first(2).map { identifier_of("posts", it) },
+ next_page: next_page_of(topic, posts.second),
+ ),
+ },
+ ),
+ ],
+ included: posts.first(2).map { post_object(it) },
+ links: links_of,
+ )
+ end
+
+ context "when the request reads the page after them" do
+ let(:resource) { JsonApiKitSpec::PostResource }
+ let(:current) { "#{base}/posts" }
+ let(:scoped_to) { topic.posts }
+ let(:params) { { page: { after: cursor_of_record(posts.second) } } }
+
+ it "returns the records after them" do
+ expect(document).to eq(
+ data: [post_object(posts.third)],
+ included: [],
+ links: links_of(prev: page_url(before: cursor_of_record(posts.third))),
+ )
+ end
+ end
+
+ context "when the page holds several rows" do
+ fab!(:another) do
+ Fabricate(:topic, title: "Another topic carrying replies", created_at: Time.utc(2026, 8, 5))
+ end
+ fab!(:more) { 3.times.map { Fabricate(:post, topic: another) } }
+
+ let(:scoped_to) { Topic.where(id: [topic.id, another.id]) }
+
+ it "renders one page of them for every row" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ another,
+ relationships: {
+ "posts" =>
+ paged_relationship_object(
+ "topics",
+ another,
+ "posts",
+ data: more.first(2).map { identifier_of("posts", it) },
+ next_page: next_page_of(another, more.second),
+ ),
+ },
+ ),
+ topic_object(
+ topic,
+ relationships: {
+ "posts" =>
+ paged_relationship_object(
+ "topics",
+ topic,
+ "posts",
+ data: posts.first(2).map { identifier_of("posts", it) },
+ next_page: next_page_of(topic, posts.second),
+ ),
+ },
+ ),
+ ],
+ included: [*more.first(2), *posts.first(2)].map { post_object(it) },
+ links: links_of,
+ )
+ end
+
+ it "reads the related records in one query" do
+ expect(track_sql_queries { document }.grep(/FROM "posts"/).size).to eq(1)
+ end
+ end
+ end
+
+ describe "one record" do
+ let(:params) { { include: %w[user] } }
+ let(:query) { { "include" => "user" } }
+ let(:current) { "#{base}/topics/#{topic.id}" }
+
+ it "renders the record with what it relates to" do
+ expect(one_document(topic.id)).to eq(
+ data:
+ topic_object(
+ topic,
+ relationships: {
+ "user" =>
+ relationship_object("topics", topic, "user", data: identifier_of("users", author)),
+ },
+ ),
+ included: [user_object(author)],
+ links: {
+ self: self_link,
+ },
+ )
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/scoping_spec.rb b/spec/integration/json_api_kit/scoping_spec.rb
new file mode 100644
index 00000000000..d51cca271e9
--- /dev/null
+++ b/spec/integration/json_api_kit/scoping_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a listing kept to other rows" do
+ include_context "with a listing of topics"
+
+ describe "the rows of another listing" do
+ let(:scoped_to) { Topic.where(id: middle.id) }
+
+ it "renders only the rows that listing holds" do
+ expect(document).to eq(data: [topic_object(middle)], included: [], links: links_of)
+ end
+
+ context "when that listing holds no row" do
+ let(:scoped_to) { Topic.where(title: "No topic carries this title") }
+
+ it "renders an empty listing" do
+ expect(document).to eq(data: [], included: [], links: links_of)
+ end
+ end
+ end
+
+ describe "the rows a resource exposes" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ scope { |guardian| Topic.secured(guardian).where(closed: true) }
+ end
+ end
+
+ it "renders only the rows its scope allows" do
+ expect(document).to eq(data: [], included: [], links: links_of)
+ end
+
+ context "when a row matches the scope" do
+ fab!(:closed) { Fabricate(:topic, closed: true, title: "A topic nobody can answer") }
+
+ it "renders that row" do
+ expect(document).to eq(
+ data: [topic_object(closed, fields: %w[title])],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the resource declares no scope of its own" do
+ let(:resource) { JsonApiKitSpec::TopicResource }
+
+ it "renders every row of its model" do
+ expect(document).to eq(
+ data: [topic_object(newest), topic_object(middle), topic_object(oldest)],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+ end
+
+ describe "the rows a related resource exposes" do
+ fab!(:open_category) { Fabricate(:category, name: "Open to everyone") }
+ fab!(:closed_category) { Fabricate(:category, name: "Kept from everyone") }
+ fab!(:filed_away) do
+ Fabricate(:topic, title: "Filed in a closed category", category: closed_category)
+ end
+
+ let(:categories) do
+ Class.new(JsonApiKit::Resource) do
+ model Category
+ type :categories
+ attribute :name
+ scope do |guardian|
+ Category.where(id: Category.where(name: "Open to everyone").select(:id))
+ end
+ end
+ end
+ let(:resource) do
+ related = categories
+
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ has_one :category, resource: related
+ end
+ end
+ let(:params) { { include: %w[category] } }
+ let(:scoped_to) { Topic.where(id: filed_away.id) }
+
+ it "renders no row that scope hides" do
+ expect(document[:included]).to be_empty
+ end
+
+ it "links to no row that scope hides" do
+ expect(document[:data].sole[:relationships]["category"][:data]).to be_nil
+ end
+ end
+
+ describe "the rows a resource exposes to the asker" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ scope { |guardian| Topic.where(user_id: guardian.user&.id) }
+ end
+ end
+
+ it "renders no row for a guardian without a user" do
+ expect(document).to eq(data: [], included: [], links: links_of)
+ end
+
+ context "when the guardian owns a row" do
+ let(:guardian) { middle.user.guardian }
+
+ it "renders that row" do
+ expect(document).to eq(
+ data: [topic_object(middle, fields: %w[title])],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/sorting_spec.rb b/spec/integration/json_api_kit/sorting_spec.rb
new file mode 100644
index 00000000000..ee721251117
--- /dev/null
+++ b/spec/integration/json_api_kit/sorting_spec.rb
@@ -0,0 +1,129 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a sorted listing" do
+ include_context "with a listing of topics"
+
+ let(:sort) { { created_at: :asc } }
+ let(:params) { { sort:, fields: { topics: [:title] } } }
+
+ it "orders the rows by the sort of the request" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+
+ context "when the sort is created_at desc" do
+ let(:sort) { { created_at: :desc } }
+
+ it "orders the rows in that direction" do
+ expect(document).to eq(
+ data: [
+ topic_object(newest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(oldest, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the sort is title asc and created_at desc" do
+ let(:sort) { { title: :asc, created_at: :desc } }
+
+ it "orders the rows by each sort in turn" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the request holds no sort" do
+ let(:params) { { fields: { topics: [:title] } } }
+
+ it "orders the rows by the sort the resource declares" do
+ expect(document).to eq(
+ data: [
+ topic_object(newest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(oldest, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the sort is a relationship" do
+ fab!(:unfiled, :private_message_topic)
+
+ let(:sort) { { "category.name" => :asc } }
+
+ it "puts the row with no related row last" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ topic_object(unfiled, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+
+ context "when the sort is last_posted_at and one row holds none" do
+ fab!(:never_posted) do
+ Fabricate(:topic, title: "Nothing has been posted here", last_posted_at: nil)
+ end
+
+ before { [oldest, middle, newest].each { it.update_columns(last_posted_at: it.created_at) } }
+
+ let(:sort) { { last_posted_at: :asc } }
+
+ it "puts the row with no value last" do
+ expect(document).to eq(
+ data: [
+ topic_object(oldest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(newest, fields: %w[title]),
+ topic_object(never_posted, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+
+ context "when the sort is last_posted_at desc" do
+ let(:sort) { { last_posted_at: :desc } }
+
+ it "puts the row with no value last" do
+ expect(document).to eq(
+ data: [
+ topic_object(newest, fields: %w[title]),
+ topic_object(middle, fields: %w[title]),
+ topic_object(oldest, fields: %w[title]),
+ topic_object(never_posted, fields: %w[title]),
+ ],
+ included: [],
+ links: links_of,
+ )
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/sparse_fieldsets_spec.rb b/spec/integration/json_api_kit/sparse_fieldsets_spec.rb
new file mode 100644
index 00000000000..bb41c6ccb30
--- /dev/null
+++ b/spec/integration/json_api_kit/sparse_fieldsets_spec.rb
@@ -0,0 +1,186 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+RSpec.describe "a document with a sparse fieldset" do
+ include_context "with a listing of topics"
+
+ let(:params) { { sort: { created_at: :asc }, page: { size: 1 }, fields: { topics: [:title] } } }
+
+ it "renders the field of the primary type it asks for" do
+ expect(document).to eq(
+ data: [topic_object(oldest, fields: %w[title])],
+ included: [],
+ links: links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+
+ context "when the request has no fieldset" do
+ let(:params) { { sort: { created_at: :asc }, page: { size: 1 } } }
+
+ it "renders every field the resource declares" do
+ expect(document).to eq(
+ data: [topic_object(oldest)],
+ included: [],
+ links:
+ links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+
+ context "when the fieldset holds an unknown field" do
+ let(:params) do
+ { sort: { created_at: :asc }, page: { size: 1 }, fields: { topics: [:secrets] } }
+ end
+
+ it "renders no attribute" do
+ expect(document).to eq(
+ data: [topic_object(oldest, fields: [])],
+ included: [],
+ links:
+ links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+
+ context "when the fieldset is on a related type" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ size: 1,
+ },
+ include: %w[user],
+ fields: {
+ users: [:username],
+ },
+ }
+ end
+
+ it "renders the related record with that field" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ oldest,
+ relationships: {
+ "user" =>
+ relationship_object(
+ "topics",
+ oldest,
+ "user",
+ data: identifier_of("users", oldest.user),
+ ),
+ },
+ ),
+ ],
+ included: [user_object(oldest.user)],
+ links:
+ links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+
+ context "when the fieldset is on a relationship to many records" do
+ fab!(:first_post) { Fabricate(:post, topic: oldest, post_number: 1) }
+
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ size: 1,
+ },
+ include: %w[posts],
+ fields: {
+ posts: [:post_number],
+ },
+ }
+ end
+
+ it "renders every related record with that field" do
+ expect(document[:included]).to eq([post_object(first_post, fields: %w[post_number])])
+ end
+ end
+
+ context "when the fieldset of a related type is empty" do
+ let(:params) do
+ { sort: { created_at: :asc }, page: { size: 1 }, include: %w[user], fields: { users: [] } }
+ end
+
+ it "renders the related record with its type and its id" do
+ expect(document).to eq(
+ data: [
+ topic_object(
+ oldest,
+ relationships: {
+ "user" =>
+ relationship_object(
+ "topics",
+ oldest,
+ "user",
+ data: identifier_of("users", oldest.user),
+ ),
+ },
+ ),
+ ],
+ included: [user_object(oldest.user, fields: [])],
+ links:
+ links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+
+ context "when the fieldset leaves a relationship out" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ page: {
+ size: 1,
+ },
+ include: %w[user],
+ fields: {
+ topics: [:title],
+ },
+ }
+ end
+
+ it "renders no relationship and no related record" do
+ expect(document).to eq(
+ data: [topic_object(oldest, fields: %w[title])],
+ included: [],
+ links:
+ links_of(next: page_url(after: cursor_of_record(oldest, sort: { created_at: :asc }))),
+ )
+ end
+ end
+
+ context "when the fieldset holds a relationship only" do
+ let(:params) { { include: %w[user], fields: { topics: %w[user] }, page: { size: 1 } } }
+ let(:query) { { "include" => "user", "fields" => { "topics" => "user" } } }
+
+ it "renders the relationship and reads the key behind it" do
+ expect(document[:data].sole[:relationships].keys).to eq(%w[user])
+ end
+ end
+
+ describe "the columns a narrow fieldset reads" do
+ subject(:columns) do
+ track_sql_queries { document }
+ .grep(/FROM "topics"/)
+ .flat_map { it[/\ASELECT (.+?) FROM/, 1].to_s.scan(/"topics"\."(\w+)"/) }
+ .flatten
+ .uniq
+ end
+
+ let(:params) { { sort: { title: :asc }, page: { size: 1 }, fields: { topics: [:title] } } }
+
+ it "reads the column it renders and the primary key" do
+ expect(columns).to contain_exactly("id", "title")
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/support.rb b/spec/integration/json_api_kit/support.rb
new file mode 100644
index 00000000000..f691f726b8c
--- /dev/null
+++ b/spec/integration/json_api_kit/support.rb
@@ -0,0 +1,207 @@
+# frozen_string_literal: true
+
+module JsonApiKitSpec
+ class GroupResource < JsonApiKit::Resource
+ model Group
+ type :groups
+
+ attribute :name
+ end
+
+ class UserResource < JsonApiKit::Resource
+ model User
+ type :users
+
+ attribute :username
+
+ has_many :groups, resource: GroupResource
+ end
+
+ GroupResource.has_many(:users, resource: UserResource)
+
+ class CategoryResource < JsonApiKit::Resource
+ model Category
+ type :categories
+
+ attribute :name
+ end
+
+ class TagResource < JsonApiKit::Resource
+ model Tag
+ type :tags
+
+ attribute :name
+ end
+
+ class PostResource < JsonApiKit::Resource
+ model Post
+ type :posts
+
+ sort :post_number
+ default_sort post_number: :asc
+ page default: 2, max: 10
+
+ attribute :post_number
+
+ has_one :user, resource: UserResource
+ end
+
+ class TopicResource < JsonApiKit::Resource
+ model Topic
+ type :topics
+
+ sort :created_at
+ sort :title
+ sort :last_posted_at
+ sort "category.name"
+ default_sort created_at: :desc
+
+ filter :title
+
+ anchor :id
+ anchor :created_at
+ anchor :title
+ anchor :last_posted_at
+ anchor(:mine) { |topics, guardian| topics.where(user_id: guardian.user&.id) }
+
+ attribute :title
+ attribute :created_at
+
+ has_one :user, resource: UserResource
+ has_one :category, resource: CategoryResource
+ has_many :tags, resource: TagResource
+ has_many :posts, resource: PostResource
+
+ includes "user.groups", "user.groups.users", "posts.topic", "posts.user", "posts.user.groups"
+ end
+
+ PostResource.has_one(:topic, resource: TopicResource)
+end
+
+RSpec.shared_context "with a listing of topics" do
+ fab!(:oldest) do
+ Fabricate(:topic, title: "Anchors and centred pages", created_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:middle) do
+ Fabricate(:topic, title: "Cursors that survive a redesign", created_at: Time.utc(2026, 8, 2))
+ end
+ fab!(:newest) do
+ Fabricate(:topic, title: "Bands of a segmented listing", created_at: Time.utc(2026, 8, 3))
+ end
+
+ let(:resource) { JsonApiKitSpec::TopicResource }
+ let(:guardian) { Guardian.new }
+ let(:params) { {} }
+ let(:base) { "https://example.com/api" }
+ let(:current) { "https://example.com/api/topics" }
+ let(:query) { {} }
+ let(:scoped_to) { nil }
+ let(:urls) { JsonApiKit::Urls.new(base:, current:, parameters: query) }
+
+ let(:document) do
+ JsonApiKit::Document::Collection.for(params, resource:, guardian:, urls:, scoped_to:).to_h
+ end
+
+ def one_document(id, **options)
+ JsonApiKit::Document::Individual.for(id, params, resource:, guardian:, urls:, **options).to_h
+ end
+
+ def listing_of(parameters)
+ JsonApiKit::Document::Collection.for(
+ parameters,
+ resource:,
+ guardian:,
+ urls: JsonApiKit::Urls.new(base:, current:),
+ scoped_to:,
+ ).to_h
+ end
+
+ def cursor_of(row) = row[:meta][:page][:cursor]
+
+ def topic_object(topic, fields: %w[title created_at], **members)
+ resource_object(
+ "topics",
+ topic,
+ { "title" => topic.title, "created_at" => topic.created_at }.slice(*fields),
+ **members,
+ )
+ end
+
+ def user_object(user, fields: %w[username], **members)
+ resource_object("users", user, { "username" => user.username }.slice(*fields), **members)
+ end
+
+ def group_object(group, fields: %w[name], **members)
+ resource_object("groups", group, { "name" => group.name }.slice(*fields), **members)
+ end
+
+ def category_object(category, fields: %w[name], **members)
+ resource_object("categories", category, { "name" => category.name }.slice(*fields), **members)
+ end
+
+ def tag_object(tag, fields: %w[name], **members)
+ resource_object("tags", tag, { "name" => tag.name }.slice(*fields), **members)
+ end
+
+ def post_object(post, fields: %w[post_number], **members)
+ resource_object("posts", post, { "post_number" => post.post_number }.slice(*fields), **members)
+ end
+
+ def resource_object(type, row, attributes, cursor: nil, relationships: nil)
+ {
+ type:,
+ id: row.id.to_s,
+ attributes: attributes.presence,
+ relationships:,
+ meta: cursor && { page: { cursor: } },
+ links: {
+ self: "#{base}/#{type}/#{row.id}",
+ },
+ }.compact
+ end
+
+ def relationship_object(type, row, name, data:)
+ {
+ data:,
+ links: {
+ self: "#{base}/#{type}/#{row.id}/relationships/#{name}",
+ related: "#{base}/#{type}/#{row.id}/#{name}",
+ },
+ }
+ end
+
+ def identifier_of(type, row) = { type:, id: row.id.to_s }
+
+ def paged_relationship_object(type, row, name, data:, next_page: nil)
+ relationship_object(type, row, name, data:).deep_merge(links: { prev: nil, next: next_page })
+ end
+
+ def refusal(title:, detail:, parameter: nil, status: "400", **members)
+ { status:, title:, detail:, source: parameter && { parameter: }, **members }.compact
+ end
+
+ def not_found = refusal(status: "404", title: "No such record", detail: "No record has this ID.")
+
+ def profile_link(name) = "https://jsonapi.org/profiles/ethanresnick/cursor-pagination/#{name}"
+
+ def self_link = query.blank? ? current : "#{current}?#{query.to_query}"
+
+ def links_of(**pages) = { self: self_link, **{ prev: nil, next: nil }.merge(pages) }
+
+ def page_url(**page) = "#{current}?#{{ page: page }.to_query}"
+
+ def cursor_at(index, rendered = document) = cursor_of(rendered[:data][index])
+
+ def cursor_of_record(record, of: resource, sort: {})
+ order = of.order(sort.transform_keys(&:to_s))
+ order.locate(of.model.where(id: record.id)).cursor.to_s
+ end
+
+ def relationship_page_url(type, row, name, **page)
+ "#{base}/#{type}/#{row.id}/#{name}?#{{ page: page }.to_query}"
+ end
+
+ def listed_ids(rendered = document) = rendered[:data].map { it[:id] }
+
+ def rendered_error(rendered = document) = rendered[:errors].sole
+end
diff --git a/spec/lib/json_api_kit/anchoring_spec.rb b/spec/lib/json_api_kit/anchoring_spec.rb
new file mode 100644
index 00000000000..45f830d8df6
--- /dev/null
+++ b/spec/lib/json_api_kit/anchoring_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Anchoring do
+ subject(:anchoring) { described_class.for(anchor) }
+
+ let(:anchor) { { id: 12 } }
+
+ describe ".for" do
+ it "returns the key as the name" do
+ expect(anchoring.name).to eq("id")
+ end
+
+ it "returns the value beside it" do
+ expect(anchoring.value).to eq(12)
+ end
+
+ context "when the key is a string" do
+ let(:anchor) { { "id" => 12 } }
+
+ it "returns the same name" do
+ expect(anchoring.name).to eq("id")
+ end
+ end
+
+ context "when the hash holds two keys" do
+ let(:anchor) { { id: 12, created_at: "2026-08-20" } }
+
+ it "returns the first pair" do
+ expect(anchoring).to have_attributes(name: "id", value: 12)
+ end
+ end
+
+ context "when the anchor is a symbol" do
+ let(:anchor) { :first_unread }
+
+ it "returns it as the name" do
+ expect(anchoring.name).to eq("first_unread")
+ end
+
+ it "returns no value" do
+ expect(anchoring.value).to be_nil
+ end
+ end
+
+ context "when the anchor is nil" do
+ let(:anchor) { nil }
+
+ it "returns nothing" do
+ expect(anchoring).to be_nil
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/association/through_spec.rb b/spec/lib/json_api_kit/association/through_spec.rb
new file mode 100644
index 00000000000..55b6225115f
--- /dev/null
+++ b/spec/lib/json_api_kit/association/through_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Association::Through do
+ subject(:association) { JsonApiKit::Schema.new(Topic).association(:tags, owner_rows) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A topic another table pairs with tags") }
+ fab!(:another_topic) { Fabricate(:topic, title: "A topic that carries the same tag") }
+ fab!(:untagged_topic) { Fabricate(:topic, title: "A topic the other table never names") }
+ fab!(:shared_tag) { Fabricate(:tag, name: "the-tag-two-topics-carry") }
+ fab!(:own_tag) { Fabricate(:tag, name: "the-tag-one-topic-carries") }
+ fab!(:other_tag) { Fabricate(:tag, name: "the-tag-no-topic-carries") }
+ fab!(:shared_tagging) { Fabricate(:topic_tag, topic:, tag: shared_tag) }
+ fab!(:own_tagging) { Fabricate(:topic_tag, topic:, tag: own_tag) }
+ fab!(:another_tagging) { Fabricate(:topic_tag, topic: another_topic, tag: shared_tag) }
+
+ let(:owner_rows) { [topic, another_topic, untagged_topic] }
+
+ describe "#related_scope" do
+ subject(:related_scope) { association.related_scope }
+
+ it "returns each row it reaches only once" do
+ expect(related_scope).to contain_exactly(shared_tag, own_tag)
+ end
+
+ it "returns rows that hold only their own columns" do
+ expect(related_scope.first.attributes.keys).to eq(Tag.column_names)
+ end
+ end
+
+ describe "#pair" do
+ subject(:pairs) { association.pair([own_tag, shared_tag, other_tag]) }
+
+ it "pairs each owner row with the rows it reaches" do
+ expect(pairs).to include(topic => [own_tag, shared_tag], another_topic => [shared_tag])
+ end
+
+ it "returns nothing for a row with no pair" do
+ expect(pairs).to include(untagged_topic => [])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/association_spec.rb b/spec/lib/json_api_kit/association_spec.rb
new file mode 100644
index 00000000000..a00d69a7223
--- /dev/null
+++ b/spec/lib/json_api_kit/association_spec.rb
@@ -0,0 +1,115 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Association do
+ subject(:association) { JsonApiKit::Schema.new(Topic).association(name, owner_rows) }
+
+ fab!(:author, :user)
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A topic that relates to rows") }
+
+ let(:name) { :user }
+ let(:owner_rows) { [topic] }
+
+ describe "#related_scope" do
+ it "returns the rows those rows reach" do
+ expect(association.related_scope).to eq([author])
+ end
+
+ context "when the page holds no row" do
+ let(:owner_rows) { [] }
+
+ it "returns none" do
+ expect(association.related_scope).to be_empty
+ end
+ end
+
+ context "when the key is on the related row" do
+ let(:name) { :posts }
+
+ fab!(:post) { Fabricate(:post, topic:) }
+
+ it "returns the rows those rows reach" do
+ expect(association.related_scope).to eq([post])
+ end
+ end
+
+ context "when the relationship narrows the rows itself" do
+ let(:name) { :first_post }
+
+ fab!(:first) { Fabricate(:post, topic:) }
+ fab!(:second) { Fabricate(:post, topic:) }
+
+ it "returns only the rows it allows" do
+ expect(association.related_scope).to eq([first])
+ end
+ end
+
+ context "when the relationship goes through another table" do
+ let(:name) { :tags }
+
+ fab!(:tag) { Fabricate(:tag, name: "a-tag-reached-through") }
+ fab!(:tagging) { Fabricate(:topic_tag, topic:, tag:) }
+
+ it "returns the rows those rows reach" do
+ expect(association.related_scope).to eq([tag])
+ end
+ end
+ end
+
+ describe "#pair" do
+ it "returns what each row relates to" do
+ expect(association.pair([author])).to eq(topic => [author])
+ end
+
+ it "returns nothing for a row that reaches none of them" do
+ expect(association.pair([])).to eq(topic => [])
+ end
+
+ context "when several rows reach the same one" do
+ fab!(:another) { Fabricate(:topic, user: author, title: "Another topic by that author") }
+
+ let(:owner_rows) { [topic, another] }
+
+ it "returns it for each of them" do
+ expect(association.pair([author])).to eq(topic => [author], another => [author])
+ end
+ end
+
+ context "when the key is on the related row" do
+ let(:name) { :posts }
+
+ fab!(:post) { Fabricate(:post, topic:) }
+ fab!(:elsewhere, :post)
+
+ it "returns only the rows that name it" do
+ expect(association.pair([post, elsewhere])).to eq(topic => [post])
+ end
+ end
+
+ context "when the relationship goes through another table" do
+ let(:name) { :tags }
+
+ fab!(:tag) { Fabricate(:tag, name: "a-tag-reached-through") }
+ fab!(:unrelated_tag) { Fabricate(:tag, name: "a-tag-nothing-carries") }
+ fab!(:tagging) { Fabricate(:topic_tag, topic:, tag:) }
+
+ it "returns only the rows the other table pairs it with" do
+ expect(association.pair([tag, unrelated_tag])).to eq(topic => [tag])
+ end
+ end
+
+ context "when a row relates to several rows" do
+ let(:name) { :tags }
+
+ fab!(:read_first) { Fabricate(:tag, name: "the-tag-read-first") }
+ fab!(:read_second) { Fabricate(:tag, name: "the-tag-read-second") }
+ fab!(:paired_first) { Fabricate(:topic_tag, topic:, tag: read_second) }
+ fab!(:paired_second) { Fabricate(:topic_tag, topic:, tag: read_first) }
+
+ it "returns them in the order the related resource read them" do
+ expect(association.pair([read_first, read_second])).to eq(
+ topic => [read_first, read_second],
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/columns_spec.rb b/spec/lib/json_api_kit/columns_spec.rb
new file mode 100644
index 00000000000..7a5228984a3
--- /dev/null
+++ b/spec/lib/json_api_kit/columns_spec.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Columns do
+ subject(:columns) { described_class.for(%i[id title]) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A row read column by column") }
+
+ let(:scope) { Topic.all }
+
+ describe ".for" do
+ context "when one of them is not known" do
+ subject(:columns) { described_class.for([:title, nil]) }
+
+ it "returns every column" do
+ expect(columns).to eq(described_class.all)
+ end
+ end
+ end
+
+ describe "#apply" do
+ subject(:rows) { columns.apply(scope) }
+
+ it "reads only those columns" do
+ expect(rows.first.attributes.keys).to contain_exactly("id", "title")
+ end
+
+ context "when it is every column" do
+ subject(:columns) { described_class.all }
+
+ it "reads the whole row" do
+ expect(rows.first.attributes.keys).to include("id", "title", "closed", "views")
+ end
+ end
+ end
+
+ describe "#with" do
+ subject(:rows) { columns.with(:created_at, :id).apply(scope) }
+
+ it "reads those columns too, each one once" do
+ expect(rows.first.attributes.keys).to contain_exactly("id", "title", "created_at")
+ end
+
+ context "when it is every column" do
+ subject(:columns) { described_class.all }
+
+ it "returns every column" do
+ expect(columns.with(:created_at)).to eq(columns)
+ end
+ end
+ end
+
+ describe "#==" do
+ it "equals the same columns" do
+ expect(columns).to eq(described_class.for(%i[id title]))
+ end
+
+ it "differs from other columns" do
+ expect(columns).not_to eq(described_class.for(%i[id]))
+ end
+
+ it "differs from every column" do
+ expect(columns).not_to eq(described_class.all)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/anchor_spec.rb b/spec/lib/json_api_kit/declarations/anchor_spec.rb
new file mode 100644
index 00000000000..5f0c6b04403
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/anchor_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Anchor do
+ subject(:anchor) { described_class.new(:created_at) }
+
+ fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
+ fab!(:newest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ sort :title
+ default_sort created_at: :asc
+ end
+ end
+ let(:order) { resource.order("created_at" => :asc) }
+ let(:guardian) { Guardian.new }
+ let(:located_row) { anchor.locate(Topic.all, value:, order:, guardian:) }
+ let(:value) { Time.utc(2026, 8, 3) }
+
+ describe "#name" do
+ it "returns the name a request anchors by" do
+ expect(anchor.name).to eq("created_at")
+ end
+ end
+
+ describe "#locatable_in?" do
+ context "when the anchor is the leading key" do
+ it { is_expected.to be_locatable_in(order) }
+ end
+
+ context "when the anchor is the primary key" do
+ subject(:anchor) { described_class.new(:id) }
+
+ it { is_expected.to be_locatable_in(order) }
+ end
+
+ context "when the resource declares how to calculate the anchor" do
+ subject(:anchor) do
+ described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
+ end
+
+ it { is_expected.to be_locatable_in(order) }
+ end
+
+ context "when the anchor is not in the order" do
+ subject(:anchor) { described_class.new(:title) }
+
+ it { is_expected.not_to be_locatable_in(order) }
+ end
+ end
+
+ describe "#locate" do
+ context "when the anchor is the leading key" do
+ it "returns the row the listing enters at that value" do
+ expect(located_row.record).to eq(newest)
+ end
+ end
+
+ context "when the anchor is the primary key" do
+ subject(:anchor) { described_class.new(:id) }
+
+ let(:value) { newest.id }
+
+ it "returns the row with that id" do
+ expect(located_row.record).to eq(newest)
+ end
+
+ context "when no row holds that id" do
+ let(:value) { -1 }
+
+ it "refuses the request" do
+ expect { located_row }.to raise_error(described_class::NoRow)
+ end
+ end
+ end
+
+ context "when the anchor is not in the order" do
+ subject(:anchor) { described_class.new(:title) }
+
+ let(:value) { newest.title }
+
+ it "refuses the request" do
+ expect { located_row }.to raise_error(ArgumentError, /title/)
+ end
+ end
+
+ context "when the resource declares how to calculate the anchor" do
+ subject(:anchor) do
+ described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
+ end
+
+ let(:guardian) { Guardian.new(newest.user) }
+ let(:value) { nil }
+
+ it "returns the row that declaration calculates for the guardian" do
+ expect(located_row.record).to eq(newest)
+ end
+ end
+ end
+
+ describe described_class::NoRow do
+ subject(:error) { described_class.new("created_at", value) }
+
+ describe "#title" do
+ it "returns the title of the error" do
+ expect(error.title).to eq("No row for the anchor")
+ end
+ end
+
+ describe "#source" do
+ it "points at that anchor" do
+ expect(error.source).to eq(parameter: "page[anchor][created_at]")
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/anchors_spec.rb b/spec/lib/json_api_kit/declarations/anchors_spec.rb
new file mode 100644
index 00000000000..a7afabc5031
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/anchors_spec.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Anchors do
+ subject(:anchors) { described_class.new(declarations, guardian:) }
+
+ let(:anchor_class) { JsonApiKit::Declarations::Anchor }
+ let(:created_at_anchor) { anchor_class.new(:created_at) }
+ let(:declarations) { [anchor_class.new(:id), created_at_anchor] }
+ let(:guardian) { Guardian.new }
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ end
+ end
+ let(:order) { resource.order("created_at" => :asc) }
+
+ describe "#fetch" do
+ subject(:anchor_declaration) { anchors.fetch("created_at") }
+
+ it "returns that anchor" do
+ expect(anchor_declaration).to be(created_at_anchor)
+ end
+
+ context "when the resource declares no anchor by that name" do
+ subject(:anchor_declaration) { anchors.fetch("secrets") }
+
+ it "refuses the request" do
+ expect { anchor_declaration }.to raise_error(KeyError)
+ end
+ end
+ end
+
+ describe "#locate" do
+ subject(:located_row) { anchors.locate(anchoring, scope:, order:) }
+
+ let(:scope) { Topic.all }
+ let(:anchoring) { JsonApiKit::Anchoring.for(created_at: Time.utc(2026, 8, 3)) }
+ let(:row) { instance_double(JsonApiKit::Pagination::Row) }
+
+ before { allow(created_at_anchor).to receive(:locate).and_return(row) }
+
+ it "asks the matching anchor to locate the row" do
+ located_row
+
+ expect(created_at_anchor).to have_received(:locate).with(
+ scope,
+ value: Time.utc(2026, 8, 3),
+ order:,
+ guardian:,
+ )
+ end
+
+ it "returns the row that anchor locates" do
+ expect(located_row).to be(row)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/attribute_spec.rb b/spec/lib/json_api_kit/declarations/attribute_spec.rb
new file mode 100644
index 00000000000..ef024a0eac3
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/attribute_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Attribute do
+ subject(:attribute) { described_class.new(:title) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A field rendered from a record") }
+
+ describe "#name" do
+ subject(:name) { attribute.name }
+
+ it "returns the name the field goes out under" do
+ expect(name).to eq("title")
+ end
+ end
+
+ describe "#value_for" do
+ subject(:value) { attribute.value_for(topic) }
+
+ it "returns what the record holds under that name" do
+ expect(value).to eq(topic.title)
+ end
+
+ context "when the attribute declares a value of its own" do
+ subject(:attribute) { described_class.new(:slug) { |record| record.title.parameterize } }
+
+ it "returns what that declaration makes of the record" do
+ expect(value).to eq("a-field-rendered-from-a-record")
+ end
+ end
+ end
+
+ describe "#column_for" do
+ subject(:column) { attribute.column_for(JsonApiKit::Schema.new(Topic)) }
+
+ it "returns the column the field reads" do
+ expect(column).to eq(:title)
+ end
+
+ context "when the attribute declares a value of its own" do
+ subject(:attribute) { described_class.new(:slug) { |record| record.title.parameterize } }
+
+ it "returns no column" do
+ expect(column).to be_nil
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/attributes_spec.rb b/spec/lib/json_api_kit/declarations/attributes_spec.rb
new file mode 100644
index 00000000000..0374b46a77a
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/attributes_spec.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Attributes do
+ subject(:attributes) { described_class.new(declarations, schema:) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A field rendered from a record", closed: false) }
+
+ let(:schema) { JsonApiKit::Schema.new(Topic) }
+ let(:attribute) { JsonApiKit::Declarations::Attribute }
+ let(:declarations) { [attribute.new(:title), attribute.new(:closed)] }
+
+ describe "#columns" do
+ subject(:columns) { attributes.columns }
+
+ it "returns the column of every field it holds" do
+ expect(columns).to eq(JsonApiKit::Columns.for(%i[title closed]))
+ end
+
+ context "when a field declares a value of its own" do
+ let(:declarations) { [attribute.new(:title), attribute.new(:slug) { |record| record.title }] }
+
+ it "returns every column" do
+ expect(columns).to eq(JsonApiKit::Columns.all)
+ end
+ end
+ end
+
+ describe "#values_for" do
+ subject(:attribute_values) { attributes.values_for(topic) }
+
+ it "returns the value of every field it holds" do
+ expect(attribute_values).to eq("title" => topic.title, "closed" => false)
+ end
+
+ context "when it holds no field" do
+ let(:declarations) { [] }
+
+ it "returns no value" do
+ expect(attribute_values).to be_empty
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/fields_spec.rb b/spec/lib/json_api_kit/declarations/fields_spec.rb
new file mode 100644
index 00000000000..317e31e1f80
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/fields_spec.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Fields do
+ subject(:fields) { described_class.for(names, attributes:, relationships:, schema:) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A record read as its fields", closed: false) }
+
+ let(:schema) { JsonApiKit::Schema.new(Topic) }
+ let(:users_resource) { Class.new(JsonApiKit::Resource) { type :users } }
+ let(:attributes) do
+ [
+ JsonApiKit::Declarations::Attribute.new(:title),
+ JsonApiKit::Declarations::Attribute.new(:closed),
+ ]
+ end
+ let(:relationships) do
+ [JsonApiKit::Declarations::Relationship::ToOne.new(:user, resource: users_resource)]
+ end
+ let(:names) { nil }
+
+ describe ".for" do
+ context "when an attribute and a relationship share a name" do
+ let(:relationships) do
+ [JsonApiKit::Declarations::Relationship::ToOne.new(:title, resource: users_resource)]
+ end
+
+ it "refuses the declaration" do
+ expect { fields }.to raise_error(described_class::Collision, /title/)
+ end
+ end
+
+ context "when two attributes share a name" do
+ let(:attributes) do
+ [
+ JsonApiKit::Declarations::Attribute.new(:title),
+ JsonApiKit::Declarations::Attribute.new(:title),
+ ]
+ end
+
+ it "refuses the declaration" do
+ expect { fields }.to raise_error(described_class::Collision, /title/)
+ end
+ end
+
+ context "when a field takes a name the kit reserves" do
+ let(:attributes) do
+ [
+ JsonApiKit::Declarations::Attribute.new(:id),
+ JsonApiKit::Declarations::Attribute.new(:type),
+ ]
+ end
+
+ it "refuses the declaration" do
+ expect { fields }.to raise_error(described_class::Collision, /id, type/)
+ end
+ end
+ end
+
+ describe "#attributes" do
+ subject(:attribute_values) { fields.attributes.values_for(topic) }
+
+ it "holds every field the resource declares" do
+ expect(attribute_values.keys).to eq(%w[title closed])
+ end
+
+ context "when the fieldset holds one field" do
+ let(:names) { %w[title] }
+
+ it "holds only those" do
+ expect(attribute_values.keys).to eq(%w[title])
+ end
+ end
+
+ context "when the fieldset is in another order" do
+ let(:names) { %w[closed title] }
+
+ it "holds them in the order the resource declares" do
+ expect(attribute_values.keys).to eq(%w[title closed])
+ end
+ end
+
+ context "when the fieldset holds an unknown field" do
+ let(:names) { %w[title secrets] }
+
+ it "leaves that name out" do
+ expect(attribute_values.keys).to eq(%w[title])
+ end
+ end
+
+ context "when the fieldset is empty" do
+ let(:names) { [] }
+
+ it "holds no field" do
+ expect(attribute_values).to be_empty
+ end
+ end
+ end
+
+ describe "#relationships" do
+ subject(:user_relationships) { fields.relationships.pick(%w[user]) }
+
+ it "holds every relationship the resource declares" do
+ expect(user_relationships.map(&:name)).to eq(%w[user])
+ end
+
+ context "when the fieldset holds an attribute only" do
+ let(:names) { %w[title] }
+
+ it "holds no relationship" do
+ expect(user_relationships).to be_empty
+ end
+ end
+
+ context "when the fieldset holds a relationship too" do
+ let(:names) { %w[title user] }
+
+ it "holds that relationship" do
+ expect(user_relationships.map(&:name)).to eq(%w[user])
+ end
+ end
+ end
+
+ describe "#columns" do
+ subject(:columns) { fields.columns }
+
+ it "returns every column" do
+ expect(columns).to eq(JsonApiKit::Columns.all)
+ end
+
+ context "when the fieldset holds one field" do
+ let(:names) { %w[title] }
+
+ it "returns the column of each one" do
+ expect(columns).to eq(JsonApiKit::Columns.for(%i[title]))
+ end
+ end
+
+ context "when the fieldset is empty" do
+ let(:names) { [] }
+
+ it "returns no column" do
+ expect(columns).to eq(JsonApiKit::Columns.for([]))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/filter/equality_spec.rb b/spec/lib/json_api_kit/declarations/filter/equality_spec.rb
new file mode 100644
index 00000000000..e74c00715a2
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/filter/equality_spec.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Filter::Equality do
+ subject(:condition) { described_class.new("title") }
+
+ fab!(:kept_topic) { Fabricate(:topic, title: "The rows a filter keeps") }
+ fab!(:also_kept) { Fabricate(:topic, title: "More rows it keeps as well") }
+ fab!(:dropped_topic) { Fabricate(:topic, title: "The rows it leaves behind") }
+
+ describe "#call" do
+ subject(:kept_ids) { condition.call(Topic.all, value).map(&:id) }
+
+ let(:value) { kept_topic.title }
+
+ it "keeps the rows whose column holds the value" do
+ expect(kept_ids).to contain_exactly(kept_topic.id)
+ end
+
+ context "when the value is an array" do
+ let(:value) { [kept_topic.title, also_kept.title] }
+
+ it "keeps the rows whose column holds one of them" do
+ expect(kept_ids).to contain_exactly(kept_topic.id, also_kept.id)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/filter_spec.rb b/spec/lib/json_api_kit/declarations/filter_spec.rb
new file mode 100644
index 00000000000..7cc6c2da59c
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/filter_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Filter do
+ subject(:filter) { described_class.new(:title) { |scope, value| scope.where(title: value) } }
+
+ fab!(:matching_topic) { Fabricate(:topic, title: "The rows a filter keeps") }
+ fab!(:dropped_topic) { Fabricate(:topic, title: "The rows it leaves behind") }
+
+ let(:scope) { Topic.all }
+
+ describe "#name" do
+ subject(:name) { filter.name }
+
+ it "returns the name a request filters by" do
+ expect(name).to eq("title")
+ end
+ end
+
+ describe "#apply" do
+ subject(:kept_ids) { filter.apply(scope, matching_topic.title).map(&:id) }
+
+ it "keeps the rows its declared condition allows" do
+ expect(kept_ids).to contain_exactly(matching_topic.id)
+ end
+
+ context "when the filter declares no condition of its own" do
+ subject(:filter) { described_class.new(:title) }
+
+ let(:equality) { instance_spy(described_class::Equality) }
+
+ before do
+ allow(described_class::Equality).to receive(:new).with("title").and_return(equality)
+ end
+
+ it "compares the column of its own name to the value" do
+ filter.apply(scope, matching_topic.title)
+
+ expect(equality).to have_received(:call).with(scope, matching_topic.title)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/filters_spec.rb b/spec/lib/json_api_kit/declarations/filters_spec.rb
new file mode 100644
index 00000000000..441ddde111d
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/filters_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Filters do
+ subject(:filters) { described_class.new(declarations) }
+
+ fab!(:open_topic) { Fabricate(:topic, title: "The rows a filter keeps", closed: false) }
+ fab!(:another_open_topic) do
+ Fabricate(:topic, title: "More rows it keeps as well", closed: false)
+ end
+ fab!(:closed_topic) { Fabricate(:topic, title: "The rows it leaves behind", closed: true) }
+
+ let(:filter_class) { JsonApiKit::Declarations::Filter }
+ let(:declarations) { [filter_class.new(:title), filter_class.new(:closed)] }
+ let(:scope) { Topic.all }
+
+ describe "#fetch" do
+ subject(:filter) { filters.fetch("title") }
+
+ it "returns that filter" do
+ expect(filter.name).to eq("title")
+ end
+
+ context "when the resource declares no filter by that name" do
+ subject(:filter) { filters.fetch("secrets") }
+
+ it "refuses the request" do
+ expect { filter }.to raise_error(KeyError)
+ end
+ end
+ end
+
+ describe "#apply" do
+ subject(:kept_ids) { filters.apply(scope, filtering).map(&:id) }
+
+ let(:filtering) { { "closed" => "false" } }
+
+ it "narrows the scope by that filter" do
+ expect(kept_ids).to contain_exactly(open_topic.id, another_open_topic.id)
+ end
+
+ context "when the filtering holds two filters" do
+ let(:filtering) { { "closed" => "false", "title" => open_topic.title } }
+
+ it "keeps only the rows every one of them allows" do
+ expect(kept_ids).to contain_exactly(open_topic.id)
+ end
+ end
+
+ context "when there is no filtering" do
+ it "returns the same scope" do
+ expect(filters.apply(scope)).to be(scope)
+ end
+ end
+
+ context "when the resource declares no filter by that name" do
+ let(:filtering) { { secrets: "x" } }
+
+ it "refuses the request" do
+ expect { kept_ids }.to raise_error(KeyError)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/include_paths_spec.rb b/spec/lib/json_api_kit/declarations/include_paths_spec.rb
new file mode 100644
index 00000000000..3510a46ebed
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/include_paths_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::IncludePaths do
+ subject(:include_paths) { described_class.new(deep_paths, relationships:) }
+
+ let(:groups_resource) { Class.new(JsonApiKit::Resource) { type :groups } }
+ let(:users_resource) do
+ related = groups_resource
+
+ Class.new(JsonApiKit::Resource) do
+ type :users
+ has_many :groups, resource: related
+ end
+ end
+ let(:user_relationship) do
+ JsonApiKit::Declarations::Relationship::ToOne.new(:user, resource: users_resource)
+ end
+ let(:tags_relationship) do
+ JsonApiKit::Declarations::Relationship::ToMany.new(:tags, resource: users_resource)
+ end
+ let(:relationships) do
+ JsonApiKit::Declarations::Relationships.new([user_relationship, tags_relationship])
+ end
+ let(:deep_paths) { %w[user.groups] }
+
+ describe ".new" do
+ context "when a path reaches a relationship no resource declares" do
+ let(:deep_paths) { %w[user.members] }
+
+ it "refuses the declaration" do
+ expect { include_paths }.to raise_error(described_class::Unresolved, /user\.members/)
+ end
+ end
+ end
+
+ describe "#allow" do
+ subject(:allow) { include_paths.allow(JsonApiKit::Paths.new(paths)) }
+
+ let(:paths) { %w[user] }
+
+ it "returns those paths" do
+ expect(allow.map(&:to_s)).to eq(%w[user])
+ end
+
+ context "when the paths hold every relationship" do
+ let(:paths) { %w[user tags] }
+
+ it "allows the request" do
+ expect { allow }.not_to raise_error
+ end
+ end
+
+ context "when the paths reach two levels deep" do
+ let(:paths) { %w[user.groups] }
+
+ it "allows the request" do
+ expect { allow }.not_to raise_error
+ end
+ end
+
+ context "when the paths are empty" do
+ let(:paths) { [] }
+
+ it "allows the request" do
+ expect { allow }.not_to raise_error
+ end
+ end
+
+ context "when a reading is part way along the path" do
+ subject(:allow) { include_paths.allow(entered_paths) }
+
+ let(:entered_paths) { JsonApiKit::Paths.new(%w[user.groups.members]).next_for("user") }
+
+ it "allows a path the resource never declares" do
+ expect { allow }.not_to raise_error
+ end
+ end
+
+ context "when the paths hold an unknown relationship" do
+ let(:paths) { %w[secrets] }
+
+ it "refuses the request" do
+ expect { allow }.to raise_error(KeyError, /secrets/)
+ end
+ end
+
+ context "when a request reads past a relationship the resource declares" do
+ let(:paths) { %w[tags.topics] }
+
+ it "refuses the request" do
+ expect { allow }.to raise_error(KeyError)
+ end
+ end
+
+ context "when a request reads past a path the resource declares" do
+ let(:paths) { %w[user.groups.users] }
+
+ it "refuses the request" do
+ expect { allow }.to raise_error(KeyError)
+ end
+ end
+ end
+
+ describe "#include?" do
+ subject { include_paths }
+
+ let(:path) { JsonApiKit::Path.for("user") }
+
+ it { is_expected.to include(path) }
+
+ context "when the path is an unknown relationship" do
+ let(:path) { JsonApiKit::Path.for("secrets") }
+
+ it { is_expected.not_to include(path) }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/relationship_spec.rb b/spec/lib/json_api_kit/declarations/relationship_spec.rb
new file mode 100644
index 00000000000..5182bae11b2
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/relationship_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec::Matchers.alias_matcher :resolve, :be_resolves
+
+RSpec.describe JsonApiKit::Declarations::Relationship do
+ subject(:relationship) { described_class.new(:user, resource: users_resource) }
+
+ fab!(:author, :user)
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A topic that relates to rows") }
+
+ let(:groups_resource) { Class.new(JsonApiKit::Resource) { type :groups } }
+ let(:users_resource) do
+ related = groups_resource
+
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ has_many :groups, resource: related
+ end
+ end
+ let(:requested) { JsonApiKit::Page::Requested.for }
+
+ describe "#listing" do
+ subject(:related_listing) { relationship.listing(params, guardian:, scoped_to:) }
+
+ let(:params) { { fields: { "users" => %w[username] } } }
+ let(:guardian) { Guardian.new(author) }
+ let(:scoped_to) { JsonApiKit::Scoping.for(User.where(id: author.id)) }
+ let(:listing) { instance_double(JsonApiKit::Query::Collection) }
+
+ before { allow(users_resource).to receive(:all).and_return(listing) }
+
+ it "asks the resource on the other side for a listing" do
+ related_listing
+
+ expect(users_resource).to have_received(:all).with(params, guardian:, scoped_to:)
+ end
+
+ it "returns the listing that resource reads" do
+ expect(related_listing).to be(listing)
+ end
+ end
+
+ describe "#resolves?" do
+ subject { relationship }
+
+ let(:path) { JsonApiKit::Path.for("groups") }
+
+ it { is_expected.to resolve(path) }
+
+ context "when the resource on the other side holds no such relationship" do
+ let(:path) { JsonApiKit::Path.for("members") }
+
+ it { is_expected.not_to resolve(path) }
+ end
+ end
+
+ describe described_class::ToOne do
+ subject(:relationship) { described_class.new(:user, resource: users_resource) }
+
+ describe "#scoping" do
+ subject(:scoping) { relationship.scoping(association) }
+
+ let(:association) { JsonApiKit::Schema.new(Topic).association(:user, [topic]) }
+
+ it "keeps the listing to the rows the owners reach" do
+ expect(scoping.apply(User.all)).to eq([author])
+ end
+
+ it "reads one page for each owner" do
+ expect(scoping.page(requested)).to be_a(JsonApiKit::Page::PerOwner)
+ end
+ end
+ end
+
+ describe described_class::ToMany do
+ subject(:relationship) { described_class.new(:posts, resource: posts_resource) }
+
+ fab!(:first_post) { Fabricate(:post, topic:) }
+ fab!(:second_post) { Fabricate(:post, topic:) }
+ fab!(:third_post) { Fabricate(:post, topic:) }
+ fab!(:elsewhere, :post)
+
+ let(:posts_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Post
+ type :posts
+ page default: 2
+ end
+ end
+
+ describe "#scoping" do
+ subject(:scoping) { relationship.scoping(association) }
+
+ let(:association) { JsonApiKit::Schema.new(Topic).association(:posts, [topic]) }
+
+ it "keeps the listing to the rows the owners reach" do
+ expect(scoping.apply(Post.all)).to contain_exactly(first_post, second_post, third_post)
+ end
+
+ it "reads one page for each owner" do
+ expect(scoping.page(requested)).to be_a(JsonApiKit::Page::PerOwner)
+ end
+ end
+
+ describe "#linkage" do
+ subject(:linkage) { relationship.linkage(records) }
+
+ let(:order) { posts_resource.order }
+ let(:records) do
+ JsonApiKit::Records.new(
+ [first_post, second_post, third_post].map do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: it, segment: order.first),
+ posts_resource.fields,
+ type: "posts",
+ )
+ end,
+ )
+ end
+
+ it "holds one page of them at the size the resource reads" do
+ expect(linkage.records.map(&:record)).to eq([first_post, second_post])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/relationships_spec.rb b/spec/lib/json_api_kit/declarations/relationships_spec.rb
new file mode 100644
index 00000000000..755d2b95339
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/relationships_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec::Matchers.alias_matcher :resolve, :be_resolves
+
+RSpec.describe JsonApiKit::Declarations::Relationships do
+ subject(:relationships) { described_class.new(declarations) }
+
+ let(:groups_resource) { Class.new(JsonApiKit::Resource) { type :groups } }
+ let(:users_resource) do
+ related = groups_resource
+
+ Class.new(JsonApiKit::Resource) do
+ type :users
+ has_many :groups, resource: related
+ end
+ end
+ let(:user_relationship) do
+ JsonApiKit::Declarations::Relationship::ToOne.new(:user, resource: users_resource)
+ end
+ let(:tags_relationship) do
+ JsonApiKit::Declarations::Relationship::ToMany.new(:tags, resource: users_resource)
+ end
+ let(:declarations) { [user_relationship, tags_relationship] }
+
+ describe "#pick" do
+ it "returns every one of them" do
+ expect(relationships.pick(%w[user tags])).to eq([user_relationship, tags_relationship])
+ end
+
+ it "leaves out the relationships a request does not name" do
+ expect(relationships.pick(%w[user])).to eq([user_relationship])
+ end
+
+ context "when the list is empty" do
+ it "returns no relationship" do
+ expect(relationships.pick([])).to be_empty
+ end
+ end
+
+ context "when it holds only one of the two" do
+ subject(:relationships) { described_class.new([tags_relationship]) }
+
+ it "leaves that name out" do
+ expect(relationships.pick(%w[user tags])).to eq([tags_relationship])
+ end
+ end
+ end
+
+ describe "#names" do
+ it "returns the name of every relationship it holds" do
+ expect(relationships.names).to eq(%w[user tags])
+ end
+ end
+
+ describe "#paths" do
+ it "returns one path for each relationship it holds" do
+ expect(relationships.paths.map(&:to_s)).to eq(%w[user tags])
+ end
+ end
+
+ describe "#resolves?" do
+ subject { relationships }
+
+ let(:path) { JsonApiKit::Path.for("user") }
+
+ it { is_expected.to resolve(path) }
+
+ context "when it holds no relationship of that name" do
+ let(:path) { JsonApiKit::Path.for("author") }
+
+ it { is_expected.not_to resolve(path) }
+ end
+
+ context "when the path reads past a relationship" do
+ let(:path) { JsonApiKit::Path.for("user.groups") }
+
+ it { is_expected.to resolve(path) }
+ end
+
+ context "when the resource on the other side holds no such relationship" do
+ let(:path) { JsonApiKit::Path.for("user.members") }
+
+ it { is_expected.not_to resolve(path) }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/sort_spec.rb b/spec/lib/json_api_kit/declarations/sort_spec.rb
new file mode 100644
index 00000000000..2f36399f5de
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/sort_spec.rb
@@ -0,0 +1,134 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Sort do
+ subject(:sort) { described_class.for(:created_at) }
+
+ describe "#name" do
+ subject(:name) { sort.name }
+
+ it { is_expected.to eq("created_at") }
+ end
+
+ describe "#key" do
+ subject(:key) { sort.key(schema: JsonApiKit::Schema.new(Topic), direction: :desc) }
+
+ it "orders by the column of the same name" do
+ expect(key.name).to eq(:created_at)
+ end
+
+ it "orders in that direction" do
+ expect(key.direction.to_sym).to eq(:desc)
+ end
+
+ context "when the column cannot be null" do
+ it { is_expected.not_to be_nullable }
+ end
+
+ context "when the column can be null" do
+ let(:sort) { described_class.for(:pinned_at) }
+
+ it { is_expected.to be_nulls_trailing }
+ end
+
+ context "with nulls: :first" do
+ let(:sort) { described_class.for(:pinned_at, nulls: :first) }
+
+ it { is_expected.to be_nulls_read_first }
+ end
+
+ context "with column" do
+ let(:sort) { described_class.for(:ran_at, column: :last_posted_at) }
+
+ it "orders by that column" do
+ expect(key.name).to eq(:last_posted_at)
+ end
+
+ it { is_expected.to be_nulls_trailing }
+ end
+
+ context "with sql" do
+ let(:sort) do
+ described_class.for(
+ :author,
+ sql: "users.username",
+ joins: "LEFT JOIN users ON users.id = topics.user_id",
+ )
+ end
+
+ it "orders by that SQL" do
+ expect(key.sql).to eq("users.username")
+ end
+
+ it "carries those joins" do
+ expect(key.joins).to eq(
+ JsonApiKit::Joins.for("LEFT JOIN users ON users.id = topics.user_id"),
+ )
+ end
+
+ it { is_expected.to be_nulls_trailing }
+ end
+
+ context "when sort is a relationship" do
+ let(:sort) { described_class.for("user.username") }
+
+ it "orders by the related column" do
+ expect(key.sql).to eq("users.username")
+ end
+
+ it "joins the association" do
+ expect(key.joins).to eq(JsonApiKit::Joins.for(:user))
+ end
+
+ it "names the key with an underscore" do
+ expect(key.name).to eq(:user_username)
+ end
+
+ it { is_expected.to be_nulls_trailing }
+
+ context "when the model has a column of that name" do
+ subject(:key) { sort.key(schema: JsonApiKit::Schema.new(Post), direction: :desc) }
+
+ let(:sort) { described_class.for("topic.id") }
+
+ it { is_expected.to be_nulls_trailing }
+ end
+
+ context "with sql" do
+ let(:sort) { described_class.for("user.username", sql: "lower(users.username)") }
+
+ it "orders by that SQL and still joins the association" do
+ expect(key.sql).to eq("lower(users.username)")
+ expect(key.joins).to eq(JsonApiKit::Joins.for(:user))
+ end
+ end
+
+ context "with joins" do
+ let(:sort) do
+ described_class.for(
+ "user.username",
+ joins: "LEFT JOIN users ON users.id = topics.user_id",
+ )
+ end
+
+ it "uses those joins and still reads the related column" do
+ expect(key.sql).to eq("users.username")
+ expect(key.joins).to eq(
+ JsonApiKit::Joins.for("LEFT JOIN users ON users.id = topics.user_id"),
+ )
+ end
+ end
+
+ context "with nulls: :first" do
+ let(:sort) { described_class.for("user.username", nulls: :first) }
+
+ it { is_expected.to be_nulls_read_first }
+ end
+
+ context "when the association doesn’t exist" do
+ let(:sort) { described_class.for("author.username") }
+
+ it { expect { key }.to raise_error(JsonApiKit::Schema::MissingAssociation, /author/) }
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/sorts_spec.rb b/spec/lib/json_api_kit/declarations/sorts_spec.rb
new file mode 100644
index 00000000000..cdea86eb497
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/sorts_spec.rb
@@ -0,0 +1,111 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Declarations::Sorts do
+ subject(:sorts) { described_class.new(declarations, schema:, default: default_sort, unique_by:) }
+
+ let(:schema) { JsonApiKit::Schema.new(Topic) }
+ let(:sort_class) { JsonApiKit::Declarations::Sort }
+ let(:declarations) do
+ [sort_class.new(:created_at), sort_class.new(:ran_at, column: :last_posted_at)]
+ end
+ let(:default_sort) { {} }
+ let(:unique_by) { [] }
+
+ describe "#fetch" do
+ subject(:sort) { sorts.fetch("created_at") }
+
+ it "returns that sort" do
+ expect(sort.name).to eq("created_at")
+ end
+
+ context "when the resource declares no sort by that name" do
+ subject(:sort) { sorts.fetch("secrets") }
+
+ it "refuses the request" do
+ expect { sort }.to raise_error(KeyError)
+ end
+ end
+ end
+
+ describe "#keyset" do
+ subject(:keyset) { sorts.keyset(ordering) }
+
+ let(:ordering) { { "created_at" => :desc } }
+
+ it "orders by that sort" do
+ expect(keyset.leading.name).to eq(:created_at)
+ end
+
+ it "reads it in that direction" do
+ expect(keyset.leading.direction.to_sym).to eq(:desc)
+ end
+
+ it "breaks its ties by the primary key of the model" do
+ expect(keyset.keys.last.name).to eq(:id)
+ end
+
+ it "reads that key in the direction of the leading key" do
+ expect(keyset.keys.last.direction.to_sym).to eq(:desc)
+ end
+
+ context "when the ordering holds two sorts" do
+ let(:ordering) { { "ran_at" => :asc, "created_at" => :desc } }
+
+ it "orders by each one in that sequence" do
+ expect(keyset.keys.map(&:name)).to eq(%i[last_posted_at created_at id])
+ end
+ end
+
+ context "when the resource declares no sort by that name" do
+ let(:ordering) { { "secrets" => :desc } }
+
+ it "refuses the request" do
+ expect { keyset }.to raise_error(KeyError)
+ end
+ end
+
+ context "when only the default sort exists" do
+ let(:ordering) { {} }
+ let(:default_sort) { { ran_at: :desc } }
+
+ it "orders by the sort the resource declares" do
+ expect(keyset.keys.map(&:name)).to eq(%i[last_posted_at id])
+ end
+ end
+
+ context "when neither the ordering nor the default sort exists" do
+ let(:ordering) { {} }
+
+ it "orders by the key that makes each row unique, upwards" do
+ expect(keyset.keys.map { [it.name, it.direction.to_sym] }).to eq([%i[id asc]])
+ end
+ end
+
+ context "when the resource declares a unique key of its own" do
+ let(:unique_by) { %i[title id] }
+
+ it "breaks ties by each column of that key in order" do
+ expect(keyset.keys.map(&:name)).to eq(%i[created_at title id])
+ end
+ end
+
+ context "when the resource declares one column as that key" do
+ let(:unique_by) { :title }
+
+ it "breaks ties by that column" do
+ expect(keyset.keys.map(&:name)).to eq(%i[created_at title])
+ end
+ end
+
+ context "when the ordering holds the key that breaks ties" do
+ let(:ordering) { { "created_at" => :desc, "id" => :asc } }
+ let(:declarations) { [sort_class.new(:created_at), sort_class.new(:id)] }
+
+ it "reads that key once in that direction" do
+ expect(keyset.keys.map { [it.name, it.direction.to_sym] }).to eq(
+ [%i[created_at desc], %i[id asc]],
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/collection_spec.rb b/spec/lib/json_api_kit/document/collection_spec.rb
new file mode 100644
index 00000000000..047f50feccd
--- /dev/null
+++ b/spec/lib/json_api_kit/document/collection_spec.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::Collection do
+ subject(:document) { described_class.new(listing, urls:) }
+
+ fab!(:first_topic) do
+ Fabricate(:topic, title: "Segments of a listing", created_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:second_topic) do
+ Fabricate(:topic, title: "Cursors and their values", created_at: Time.utc(2026, 8, 2))
+ end
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ attribute :title
+ end
+ end
+ let(:guardian) { Guardian.new }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")
+ end
+ let(:params) { {} }
+ let(:listing) { resource.all(params, guardian:) }
+ let(:primary_data) { document.to_h[:data] }
+ let(:first_record) { listing.records.to_a.first }
+ let(:second_record) { listing.records.to_a.last }
+
+ describe "#to_h" do
+ before { allow(JsonApiKit::Document::ResourceObject).to receive(:new).and_call_original }
+
+ it "renders the records as data" do
+ expect(primary_data.map { it[:id] }).to eq([first_topic.id.to_s, second_topic.id.to_s])
+ end
+
+ it "renders each record with no page meta" do
+ document.to_h
+
+ expect(JsonApiKit::Document::ResourceObject).to have_received(:new).with(
+ first_record,
+ urls:,
+ meta: {
+ },
+ )
+ expect(JsonApiKit::Document::ResourceObject).to have_received(:new).with(
+ second_record,
+ urls:,
+ meta: {
+ },
+ )
+ end
+
+ context "when the request asks for the cursor of each row" do
+ let(:params) { { page: { item_cursors: true } } }
+
+ it "renders each record with its cursor" do
+ document.to_h
+
+ expect(JsonApiKit::Document::ResourceObject).to have_received(:new).with(
+ first_record,
+ urls:,
+ meta: {
+ page: {
+ cursor: first_record.cursor.to_s,
+ },
+ },
+ )
+ expect(JsonApiKit::Document::ResourceObject).to have_received(:new).with(
+ second_record,
+ urls:,
+ meta: {
+ page: {
+ cursor: second_record.cursor.to_s,
+ },
+ },
+ )
+ end
+ end
+
+ context "when the listing reads no row" do
+ let(:listing) { resource.all({}, guardian:, scoped_to: Topic.where(id: -1)) }
+
+ it "renders an empty document" do
+ expect(document.to_h).to eq(
+ data: [],
+ included: [],
+ links: {
+ self: "https://example.com/api/topics",
+ prev: nil,
+ next: nil,
+ },
+ )
+ end
+ end
+
+ context "when a page lies at each end of the listing" do
+ fab!(:third_topic) do
+ Fabricate(:topic, title: "Links to the pages at each end", created_at: Time.utc(2026, 8, 3))
+ end
+
+ let(:first_page) { resource.all({ page: { size: 1 } }, guardian:) }
+ let(:listing) do
+ resource.all({ page: { size: 1, after: first_page.records.first.cursor.to_s } }, guardian:)
+ end
+ let(:page_cursor) { listing.records.first.cursor }
+
+ it "renders a link to the page at each end" do
+ expect(document.to_h[:links]).to eq(
+ self: "https://example.com/api/topics",
+ prev: "https://example.com/api/topics?page%5Bbefore%5D=#{page_cursor}",
+ next: "https://example.com/api/topics?page%5Bafter%5D=#{page_cursor}",
+ )
+ end
+ end
+
+ context "when a request asks for a relationship" do
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ end
+ end
+ let(:resource) { Class.new(super()).tap { it.has_one(:user, resource: users_resource) } }
+ let(:listing) { resource.all({ include: %w[user] }, guardian:) }
+
+ it "renders every related record" do
+ expect(document.to_h[:included].map { it[:id] }).to contain_exactly(
+ first_topic.user_id.to_s,
+ second_topic.user_id.to_s,
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/contents_spec.rb b/spec/lib/json_api_kit/document/contents_spec.rb
new file mode 100644
index 00000000000..d8e1ae1c787
--- /dev/null
+++ b/spec/lib/json_api_kit/document/contents_spec.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::Contents do
+ subject(:contents) { described_class.new(records, related_records) }
+
+ fab!(:author, :user)
+ fab!(:group) { Fabricate(:group, name: "the_authors_group") }
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A topic a document renders") }
+ fab!(:other_topic) { Fabricate(:topic, title: "A second topic a document renders") }
+
+ let(:author_record) { record_of(author, "users") }
+ let(:other_topic_record) { record_of(other_topic, "topics") }
+ let(:records) { [record_of(topic, "topics", "user" => linkage(author_record))] }
+ let(:related_records) { [author_record] }
+
+ def record_of(model, type, relationships = {})
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: model, segment: nil),
+ JsonApiKit::Declarations::Fields.for(
+ nil,
+ attributes: [],
+ relationships: [],
+ schema: JsonApiKit::Schema.new(model.class),
+ ),
+ type:,
+ relationships:,
+ )
+ end
+
+ def linkage(*records) = JsonApiKit::Linkage.new(records)
+
+ describe "#primary" do
+ it "returns the records a caller asks for" do
+ expect(contents.primary.map(&:record)).to eq([topic])
+ end
+
+ context "when a path reads a primary record a second time" do
+ let(:related_records) { [author_record, record_of(topic, "topics", "tags" => linkage)] }
+
+ it "holds the relationships of both readings" do
+ expect(contents.primary.first.relationships.keys).to contain_exactly("user", "tags")
+ end
+ end
+
+ context "when a caller asks for more than one record" do
+ let(:records) { [*super(), other_topic_record] }
+
+ it "keeps the order a caller asks for" do
+ expect(contents.primary.map(&:record)).to eq([topic, other_topic])
+ end
+ end
+ end
+
+ describe "#related" do
+ it "returns the records the data relates to" do
+ expect(contents.related.map(&:record)).to eq([author])
+ end
+
+ context "when a path reads a primary record a second time" do
+ let(:related_records) { [author_record, record_of(topic, "topics")] }
+
+ it "drops that record" do
+ expect(contents.related.map(&:record)).to eq([author])
+ end
+ end
+
+ context "when a caller asks for more than one record" do
+ let(:records) { [*super(), other_topic_record] }
+
+ it "leaves out every record a caller asks for" do
+ expect(contents.related.map(&:record)).to eq([author])
+ end
+ end
+
+ context "when a caller asks for no record" do
+ let(:records) { [] }
+ let(:related_records) { [author_record, other_topic_record] }
+
+ it "returns every record" do
+ expect(contents.related.map(&:record)).to eq([author, other_topic])
+ end
+ end
+
+ context "when two paths read one record" do
+ let(:related_records) do
+ [author_record, record_of(author, "users", "groups" => linkage(record_of(group, "groups")))]
+ end
+
+ it "returns it one time" do
+ expect(contents.related.map(&:record)).to eq([author])
+ end
+
+ it "holds the relationships of both readings" do
+ expect(contents.related.first.relationships.keys).to contain_exactly("groups")
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/error_object_spec.rb b/spec/lib/json_api_kit/document/error_object_spec.rb
new file mode 100644
index 00000000000..bb280809638
--- /dev/null
+++ b/spec/lib/json_api_kit/document/error_object_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::ErrorObject do
+ subject(:error_object) { described_class.new(error) }
+
+ let(:error_class) do
+ Class.new(JsonApiKit::BadRequest) do
+ def title = "Page size is too large"
+
+ def source = { parameter: "page[size]" }
+
+ def type = "https://example.com/errors/max-size"
+
+ def meta = { page: { maxSize: 50 } }
+ end
+ end
+ let(:error) { error_class.new("Page size 100 exceeds the maximum of 50.") }
+
+ describe "#to_h" do
+ it "renders every member of the error" do
+ expect(error_object.to_h).to eq(
+ status: "400",
+ title: "Page size is too large",
+ detail: "Page size 100 exceeds the maximum of 50.",
+ source: {
+ parameter: "page[size]",
+ },
+ links: {
+ type: "https://example.com/errors/max-size",
+ },
+ meta: {
+ page: {
+ maxSize: 50,
+ },
+ },
+ )
+ end
+
+ context "when the error holds no source, type or meta" do
+ let(:error) { JsonApiKit::NotFound.new }
+
+ it "drops every empty member" do
+ expect(error_object.to_h).to eq(
+ status: "404",
+ title: "No such record",
+ detail: "No record has this ID.",
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/errors_spec.rb b/spec/lib/json_api_kit/document/errors_spec.rb
new file mode 100644
index 00000000000..b56ff27ff5d
--- /dev/null
+++ b/spec/lib/json_api_kit/document/errors_spec.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::Errors do
+ subject(:document) { described_class.new(not_found, bad_request) }
+
+ let(:not_found) { JsonApiKit::NotFound.new }
+ let(:bad_request) { JsonApiKit::BadRequest.new("Page size must be an integer.") }
+
+ describe "#status" do
+ it "returns the status of the first error" do
+ expect(document.status).to eq("404")
+ end
+ end
+
+ describe "#to_h" do
+ it "renders every error in order" do
+ expect(document.to_h[:errors].map { it[:title] }).to eq(["No such record", "Bad request"])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/individual_spec.rb b/spec/lib/json_api_kit/document/individual_spec.rb
new file mode 100644
index 00000000000..7555aa0d72b
--- /dev/null
+++ b/spec/lib/json_api_kit/document/individual_spec.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::Individual do
+ subject(:document) { described_class.new(reading, urls:) }
+
+ fab!(:topic) { Fabricate(:topic, title: "One record read on its own") }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ end
+ end
+ let(:guardian) { Guardian.new }
+ let(:urls) do
+ JsonApiKit::Urls.new(
+ base: "https://example.com/api",
+ current: "https://example.com/api/topics/1",
+ )
+ end
+ let(:reading) { resource.find(topic.id, guardian:) }
+
+ describe "#to_h" do
+ it "renders the record as a document" do
+ expect(document.to_h).to eq(
+ data: {
+ type: "topics",
+ id: topic.id.to_s,
+ attributes: {
+ "title" => topic.title,
+ },
+ links: {
+ self: "https://example.com/api/topics/#{topic.id}",
+ },
+ },
+ included: [],
+ links: {
+ self: "https://example.com/api/topics/1",
+ },
+ )
+ end
+
+ context "when a request asks for a relationship" do
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ end
+ end
+ let(:resource) { Class.new(super()).tap { it.has_one(:user, resource: users_resource) } }
+ let(:reading) { resource.find(topic.id, { include: %w[user] }, guardian:) }
+
+ it "renders the related record" do
+ expect(document.to_h[:included].map { it[:id] }).to eq([topic.user_id.to_s])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/page_links_spec.rb b/spec/lib/json_api_kit/document/page_links_spec.rb
new file mode 100644
index 00000000000..c60a75ffbec
--- /dev/null
+++ b/spec/lib/json_api_kit/document/page_links_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::PageLinks do
+ subject(:page_links) { described_class.new(url, pages) }
+
+ let(:url) { JsonApiKit::Url.new("https://example.com/api/topics") }
+ let(:pages) { { before: "read-back-here", after: "read-on-here" } }
+
+ describe "#to_h" do
+ subject(:links) { page_links.to_h }
+
+ it "returns a link to the page at each end" do
+ expect(links).to eq(
+ prev: "https://example.com/api/topics?page%5Bbefore%5D=read-back-here",
+ next: "https://example.com/api/topics?page%5Bafter%5D=read-on-here",
+ )
+ end
+
+ context "when no page follows the records" do
+ let(:pages) { super().merge(after: nil) }
+
+ it "returns no next link" do
+ expect(links[:next]).to be_nil
+ end
+ end
+
+ context "when no page comes before the records" do
+ let(:pages) { super().merge(before: nil) }
+
+ it "returns a next link only" do
+ expect(links).to eq(
+ prev: nil,
+ next: "https://example.com/api/topics?page%5Bafter%5D=read-on-here",
+ )
+ end
+ end
+
+ context "when there is no page" do
+ let(:pages) { {} }
+
+ it { is_expected.to be_empty }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/relationship_object_spec.rb b/spec/lib/json_api_kit/document/relationship_object_spec.rb
new file mode 100644
index 00000000000..39b5afd0db3
--- /dev/null
+++ b/spec/lib/json_api_kit/document/relationship_object_spec.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::RelationshipObject do
+ subject(:relationship_object) { described_class.new(linkage, urls:, owner:, name: "posts") }
+
+ fab!(:author, :user)
+ fab!(:topic)
+
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")
+ end
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ end
+ end
+ let(:topics_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ end
+ let(:record) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: author, segment: nil),
+ users_resource.fields,
+ type: "users",
+ )
+ end
+ let(:owner) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ topics_resource.fields,
+ type: "topics",
+ )
+ end
+ let(:linkage) { JsonApiKit::Linkage::ToOne.new([record]) }
+ let(:relationship_url) { "https://example.com/api/topics/#{topic.id}/relationships/posts" }
+ let(:related_url) { "https://example.com/api/topics/#{topic.id}/posts" }
+
+ describe "#to_h" do
+ it "renders the record it links to" do
+ expect(relationship_object.to_h[:data]).to eq(type: "users", id: author.id.to_s)
+ end
+
+ it "renders the relationship link and the related link" do
+ expect(relationship_object.to_h[:links]).to eq(self: relationship_url, related: related_url)
+ end
+
+ context "when the relationship holds a page of records" do
+ let(:page) do
+ JsonApiKit::Records::Page.new(JsonApiKit::Records.new([record]), "read-on-here")
+ end
+ let(:linkage) { JsonApiKit::Linkage::ToMany.new(page, previous_page: "read-back-here") }
+
+ it "renders a page link at each end" do
+ expect(relationship_object.to_h[:links]).to eq(
+ self: relationship_url,
+ related: related_url,
+ prev: "#{relationship_url}?page%5Bbefore%5D=read-back-here",
+ next: "#{relationship_url}?page%5Bafter%5D=read-on-here",
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document/resource_object_spec.rb b/spec/lib/json_api_kit/document/resource_object_spec.rb
new file mode 100644
index 00000000000..d2a45967139
--- /dev/null
+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document::ResourceObject do
+ subject(:resource_object) { described_class.new(record, urls:, meta:) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A row a document renders") }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ end
+ end
+ let(:fields) { resource.fields }
+ let(:row) { JsonApiKit::Pagination::Row.new(record: topic, segment: nil) }
+ let(:record) { JsonApiKit::Record.new(row, fields, type: "topics") }
+ let(:meta) { {} }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")
+ end
+
+ describe "#to_h" do
+ it "renders the type, the id and the attributes" do
+ expect(resource_object.to_h).to eq(
+ type: "topics",
+ id: topic.id.to_s,
+ attributes: {
+ "title" => topic.title,
+ },
+ links: {
+ self: "https://example.com/api/topics/#{topic.id}",
+ },
+ )
+ end
+
+ context "when a caller gives it meta" do
+ let(:meta) { { page: { cursor: "the-cursor" } } }
+
+ it "renders the meta" do
+ expect(resource_object.to_h[:meta]).to eq(page: { cursor: "the-cursor" })
+ end
+ end
+
+ context "when the record holds no attribute" do
+ let(:fields) { resource.fields(["secrets"]) }
+
+ it "renders no attributes" do
+ expect(resource_object.to_h).not_to have_key(:attributes)
+ end
+ end
+
+ context "when the record holds a relationship" do
+ let(:record) do
+ JsonApiKit::Record.new(row, fields, type: "topics", relationships: { "user" => linkage })
+ end
+ let(:linkage) { JsonApiKit::Linkage::ToOne.new([author_record]) }
+ let(:author_record) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: topic.user, segment: nil),
+ users_resource.fields,
+ type: "users",
+ )
+ end
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ end
+ end
+
+ before { allow(JsonApiKit::Document::RelationshipObject).to receive(:new).and_call_original }
+
+ it "renders the relationship under its own name" do
+ expect(resource_object.to_h[:relationships].keys).to eq(["user"])
+ end
+
+ it "renders the linkage the record holds" do
+ resource_object.to_h
+
+ expect(JsonApiKit::Document::RelationshipObject).to have_received(:new).with(
+ linkage,
+ urls:,
+ owner: record,
+ name: "user",
+ )
+ end
+ end
+
+ context "when the record holds a relationship to many records" do
+ fab!(:post)
+
+ let(:posts_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Post
+ type :posts
+ end
+ end
+ let(:post_record) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: post, segment: nil),
+ posts_resource.fields,
+ type: "posts",
+ )
+ end
+ let(:page) { JsonApiKit::Records::Page.new(JsonApiKit::Records.new([post_record]), nil) }
+ let(:linkage) { JsonApiKit::Linkage::ToMany.new(page) }
+ let(:record) do
+ JsonApiKit::Record.new(row, fields, type: "topics", relationships: { "posts" => linkage })
+ end
+
+ it "renders every record it links to" do
+ expect(resource_object.to_h[:relationships]["posts"][:data]).to eq(
+ [{ type: "posts", id: post.id.to_s }],
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/document_spec.rb b/spec/lib/json_api_kit/document_spec.rb
new file mode 100644
index 00000000000..83aec6f2255
--- /dev/null
+++ b/spec/lib/json_api_kit/document_spec.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Document do
+ fab!(:topic) do
+ Fabricate(:topic, title: "A topic a document renders", created_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:other_topic) do
+ Fabricate(:topic, title: "A topic a scope leaves out", created_at: Time.utc(2026, 8, 2))
+ end
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ attribute :title
+ end
+ end
+ let(:guardian) { Guardian.new }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")
+ end
+ let(:parameters) { {} }
+
+ describe "Collection.for" do
+ subject(:document) do
+ JsonApiKit::Document::Collection.for(parameters, resource:, guardian:, urls:, scoped_to:)
+ end
+
+ let(:scoped_to) { nil }
+ let(:listed_ids) { document.to_h[:data].map { it[:id] } }
+
+ it "renders every record of the listing" do
+ expect(listed_ids).to eq([topic.id.to_s, other_topic.id.to_s])
+ end
+
+ it "returns the status of a rendered document" do
+ expect(document.status).to eq("200")
+ end
+
+ context "when a caller narrows the listing with a scope" do
+ let(:scoped_to) { Topic.where(id: topic.id) }
+
+ it "renders the records that scope holds" do
+ expect(listed_ids).to eq([topic.id.to_s])
+ end
+ end
+
+ context "when the contract refuses the request" do
+ let(:parameters) { { sort: { secrets: :asc } } }
+
+ it { is_expected.to be_a(JsonApiKit::Document::Errors) }
+
+ it "renders the error as a document" do
+ expect(document.to_h[:errors].sole).to include(status: "400", title: "No such sort")
+ end
+ end
+ end
+
+ describe "Individual.for" do
+ subject(:document) do
+ JsonApiKit::Document::Individual.for(id, parameters, resource:, guardian:, urls:)
+ end
+
+ let(:id) { topic.id }
+
+ it "renders the record as a document" do
+ expect(document.to_h[:data][:id]).to eq(topic.id.to_s)
+ end
+
+ context "when no row holds that id" do
+ let(:id) { -1 }
+
+ it { is_expected.to be_a(JsonApiKit::Document::Errors) }
+
+ it "renders the error as a document" do
+ expect(document.to_h[:errors].sole).to include(status: "404", title: "No such record")
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/included_spec.rb b/spec/lib/json_api_kit/included_spec.rb
new file mode 100644
index 00000000000..103ae67a4f9
--- /dev/null
+++ b/spec/lib/json_api_kit/included_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Included do
+ subject(:included) { described_class.for(records) }
+
+ fab!(:author, :user)
+ fab!(:group) { Fabricate(:group, name: "the_authors_group") }
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A topic that holds relations") }
+ fab!(:another) { Fabricate(:topic, user: author, title: "Another topic by that author") }
+
+ let(:author_record) { record_of(author, "users") }
+ let(:records) { [record_of(topic, "topics", "user" => linkage(author_record))] }
+
+ def record_of(model, type, relationships = {})
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: model, segment: nil),
+ JsonApiKit::Declarations::Fields.for(
+ nil,
+ attributes: [],
+ relationships: [],
+ schema: JsonApiKit::Schema.new(model.class),
+ ),
+ type:,
+ relationships:,
+ )
+ end
+
+ def linkage(*records) = JsonApiKit::Linkage.new(records)
+
+ it "holds the records that these records relate to" do
+ expect(included.map(&:record)).to eq([author])
+ end
+
+ context "when nothing relates to anything" do
+ let(:records) { [record_of(topic, "topics")] }
+
+ it "holds nothing" do
+ expect(included).to be_empty
+ end
+ end
+
+ context "when two records relate to one record" do
+ let(:records) do
+ [
+ record_of(topic, "topics", "user" => linkage(author_record)),
+ record_of(another, "topics", "user" => linkage(record_of(author, "users"))),
+ ]
+ end
+
+ it "holds it for each of them" do
+ expect(included.map(&:record)).to eq([author, author])
+ end
+ end
+
+ context "when two records share a type and nothing else" do
+ let(:records) do
+ [record_of(topic, "topics", "user" => linkage(author_record, record_of(hidden, "users")))]
+ end
+
+ fab!(:hidden, :user)
+
+ it "holds each of them" do
+ expect(included.map(&:record)).to eq([author, hidden])
+ end
+ end
+
+ context "when a related record relates to another one" do
+ let(:author_record) do
+ record_of(author, "users", "groups" => linkage(record_of(group, "groups")))
+ end
+
+ it "holds the records past the first" do
+ expect(included.map(&:record)).to eq([author, group])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/joins_spec.rb b/spec/lib/json_api_kit/joins_spec.rb
new file mode 100644
index 00000000000..1ed035db208
--- /dev/null
+++ b/spec/lib/json_api_kit/joins_spec.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Joins do
+ subject(:joins) { described_class.for(declarations) }
+
+ fab!(:section) { Fabricate(:category, name: "A section of the forum") }
+ fab!(:filed) { Fabricate(:topic, category: section) }
+ fab!(:unfiled, :private_message_topic)
+
+ let(:declarations) { [] }
+ let(:scope) { Topic.where(id: [filed.id, unfiled.id]) }
+ let(:statement) { "LEFT JOIN categories ON categories.id = topics.category_id" }
+
+ describe ".for" do
+ context "with a Joins" do
+ it "returns the same object" do
+ expect(described_class.for(joins)).to be(joins)
+ end
+ end
+
+ context "with one declaration" do
+ let(:declarations) { :category }
+
+ it "joins it" do
+ expect(joins.apply(scope).to_sql).to include("LEFT OUTER JOIN")
+ end
+ end
+ end
+
+ describe "#apply" do
+ context "with no declarations" do
+ it "leaves the scope alone" do
+ expect(joins.apply(scope).to_sql).to eq(scope.to_sql)
+ end
+ end
+
+ context "with an association" do
+ let(:declarations) { [:category] }
+
+ it "joins it without dropping rows" do
+ expect(joins.apply(scope).map(&:id)).to contain_exactly(filed.id, unfiled.id)
+ end
+ end
+
+ context "with a SQL statement" do
+ let(:declarations) { [statement] }
+
+ it "joins with it" do
+ expect(joins.apply(scope).where("categories.name IS NULL").map(&:id)).to eq([unfiled.id])
+ end
+ end
+
+ context "with both" do
+ let(:declarations) { [statement, :category] }
+
+ it "applies both" do
+ expect(joins.apply(scope).to_sql).to include("LEFT JOIN categories", "LEFT OUTER JOIN")
+ end
+ end
+ end
+
+ describe "#+" do
+ subject(:merged) { joins + described_class.for(:category) }
+
+ let(:declarations) { [statement] }
+
+ it "merges both joins" do
+ expect(merged).to eq(described_class.for([statement, :category]))
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/linkage/to_many_spec.rb b/spec/lib/json_api_kit/linkage/to_many_spec.rb
new file mode 100644
index 00000000000..dc7e0b55989
--- /dev/null
+++ b/spec/lib/json_api_kit/linkage/to_many_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Linkage::ToMany do
+ subject(:linkage) { described_class.new(page, previous_page:) }
+
+ fab!(:topic)
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ end
+ let(:record) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ resource.fields,
+ type: "topics",
+ )
+ end
+ let(:records) { [record] }
+ let(:next_page) { JsonApiKit::Pagination::Cursor.new([2]) }
+ let(:previous_page) { JsonApiKit::Pagination::Cursor.new([1]) }
+ let(:page) { JsonApiKit::Records::Page.new(JsonApiKit::Records.new(records), next_page) }
+
+ describe "#collapse" do
+ it "returns every record it holds" do
+ expect(linkage.collapse { it.id }).to eq([topic.id.to_s])
+ end
+
+ context "when it holds no record" do
+ let(:records) { [] }
+
+ it "returns an empty list" do
+ expect(linkage.collapse { it.id }).to eq([])
+ end
+ end
+ end
+
+ describe "#pages" do
+ it "returns the cursor at each end as a string" do
+ expect(linkage.pages).to eq(before: previous_page.to_s, after: next_page.to_s)
+ end
+
+ context "when no page lies either side" do
+ let(:next_page) { nil }
+ let(:previous_page) { nil }
+
+ it "returns nothing at each end" do
+ expect(linkage.pages).to eq(before: nil, after: nil)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/linkage/to_one_spec.rb b/spec/lib/json_api_kit/linkage/to_one_spec.rb
new file mode 100644
index 00000000000..f82f79d0159
--- /dev/null
+++ b/spec/lib/json_api_kit/linkage/to_one_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Linkage::ToOne do
+ subject(:linkage) { described_class.new(records) }
+
+ fab!(:topic)
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ end
+ let(:record) do
+ JsonApiKit::Record.new(
+ JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ resource.fields,
+ type: "topics",
+ )
+ end
+ let(:records) { [record] }
+
+ describe "#collapse" do
+ it "returns what the block makes of its one record" do
+ expect(linkage.collapse { it.id }).to eq(topic.id.to_s)
+ end
+
+ context "when it holds no record" do
+ let(:records) { [] }
+
+ it "returns nothing" do
+ expect(linkage.collapse { it.id }).to be_nil
+ end
+ end
+ end
+
+ describe "#pages" do
+ it "returns no page" do
+ expect(linkage.pages).to be_empty
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/page/limits_spec.rb b/spec/lib/json_api_kit/page/limits_spec.rb
new file mode 100644
index 00000000000..eb25f57364c
--- /dev/null
+++ b/spec/lib/json_api_kit/page/limits_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Page::Limits do
+ subject(:limits) { described_class.new(default: 20, max: 50) }
+
+ describe ".new" do
+ it "refuses a default the maximum forbids" do
+ expect { described_class.new(default: 200, max: 50) }.to raise_error(
+ described_class::OutOfRange,
+ )
+ end
+
+ it "refuses a default below one" do
+ expect { described_class.new(default: 0, max: 50) }.to raise_error(
+ described_class::OutOfRange,
+ )
+ end
+
+ it "refuses a maximum below one" do
+ expect { described_class.new(max: 0) }.to raise_error(described_class::OutOfRange)
+ end
+ end
+
+ describe "#size" do
+ subject(:size) { limits.size(page_size) }
+
+ let(:page_size) { 10 }
+
+ it "returns the size a request asks for" do
+ expect(size).to eq(10)
+ end
+
+ context "when a request asks for none" do
+ let(:page_size) { nil }
+
+ it "returns the resource's default size" do
+ expect(size).to eq(20)
+ end
+ end
+
+ context "when the resource declares a maximum below the kit's default size" do
+ subject(:limits) { described_class.new(max: 10) }
+
+ let(:page_size) { nil }
+
+ it "returns the maximum" do
+ expect(size).to eq(10)
+ end
+ end
+
+ context "when the resource declares no limits of its own" do
+ subject(:limits) { described_class.new }
+
+ let(:page_size) { nil }
+
+ it "returns the kit's default size" do
+ expect(size).to eq(described_class::DEFAULT)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/around_spec.rb b/spec/lib/json_api_kit/pagination/around_spec.rb
new file mode 100644
index 00000000000..148453922c7
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/around_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Around do
+ subject(:page) { described_class.new(scope, order:, row:, before:, after:, include_row:) }
+
+ fab!(:first_topic, :topic)
+ fab!(:second_topic, :topic)
+ fab!(:third_topic, :topic)
+ fab!(:fourth_topic, :topic)
+ fab!(:fifth_topic, :topic)
+
+ let(:model) { Topic }
+ let(:topics) { [first_topic, second_topic, third_topic, fourth_topic, fifth_topic] }
+ let(:order) do
+ JsonApiKit::Pagination::Order.new(
+ JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)]),
+ )
+ end
+ let(:scope) { Topic.where(id: topics.map(&:id)) }
+ let(:anchor_topic) { third_topic }
+ let(:row) { order.locate(scope.where(id: anchor_topic.id)) }
+ let(:second_cursor) { order.first.position_of(second_topic).to_cursor }
+ let(:third_cursor) { order.first.position_of(third_topic).to_cursor }
+ let(:fourth_cursor) { order.first.position_of(fourth_topic).to_cursor }
+ let(:before) { 1 }
+ let(:after) { 1 }
+ let(:include_row) { true }
+
+ describe "#rows" do
+ subject(:records) { page.rows.map(&:record) }
+
+ it "reads the rows around the anchor in the order of the listing" do
+ expect(records).to eq([second_topic, third_topic, fourth_topic])
+ end
+
+ it "puts the anchor row itself between the two pages" do
+ expect(page.rows[1]).to be(row)
+ end
+
+ context "when the caller leaves the anchor row out" do
+ let(:include_row) { false }
+
+ it "leaves the anchor row out of the page" do
+ expect(records).to eq([second_topic, fourth_topic])
+ end
+ end
+
+ context "when the caller asks for no row before the anchor" do
+ let(:before) { 0 }
+
+ it "reads only the rows after the anchor" do
+ expect(records).to eq([third_topic, fourth_topic])
+ end
+ end
+
+ context "when the caller asks for more rows than the listing holds" do
+ let(:before) { 10 }
+ let(:after) { 10 }
+
+ it "reads every row of the listing" do
+ expect(records).to eq(topics)
+ end
+ end
+ end
+
+ describe "#next" do
+ subject(:next_page) { page.next }
+
+ it "returns the cursor of the last row after the anchor" do
+ expect(next_page).to eq(fourth_cursor)
+ end
+
+ context "when the anchor is the last row of the listing" do
+ let(:anchor_topic) { fifth_topic }
+
+ it "returns no cursor" do
+ expect(next_page).to be_nil
+ end
+ end
+
+ context "when the caller asks for no row after the anchor" do
+ let(:after) { 0 }
+
+ it "returns the cursor of the anchor row" do
+ expect(next_page).to eq(third_cursor)
+ end
+ end
+ end
+
+ describe "#previous" do
+ subject(:previous_page) { page.previous }
+
+ it "returns the cursor of the first row before the anchor" do
+ expect(previous_page).to eq(second_cursor)
+ end
+
+ context "when the anchor is the first row of the listing" do
+ let(:anchor_topic) { first_topic }
+
+ it "returns no cursor" do
+ expect(previous_page).to be_nil
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/cursor_spec.rb b/spec/lib/json_api_kit/pagination/cursor_spec.rb
new file mode 100644
index 00000000000..da252363a2f
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/cursor_spec.rb
@@ -0,0 +1,185 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Cursor do
+ subject(:cursor) { described_class.new(values) }
+
+ let(:values) { [42, "alice"] }
+
+ describe ".coerce" do
+ subject(:cursor_value) { described_class.coerce(value) }
+
+ context "with a number" do
+ let(:value) { 42 }
+
+ it { is_expected.to eq(42) }
+ end
+
+ context "with a string" do
+ let(:value) { "alice" }
+
+ it { is_expected.to eq("alice") }
+ end
+
+ context "with nil" do
+ let(:value) { nil }
+
+ it { is_expected.to be_nil }
+ end
+
+ context "with a boolean" do
+ let(:value) { false }
+
+ it { is_expected.to be(false) }
+ end
+
+ context "with a timestamp" do
+ let(:value) { Time.utc(2026, 8, 3, 12, 0, 0, 123_456) }
+
+ it "writes it to the microsecond" do
+ expect(cursor_value).to eq("2026-08-03T12:00:00.123456Z")
+ end
+ end
+
+ context "when the timestamp carries a zone" do
+ let(:value) { Time.utc(2026, 8, 3, 12, 0, 0, 123_456).in_time_zone("Europe/Paris") }
+
+ it "writes the same instant in UTC" do
+ expect(cursor_value).to eq("2026-08-03T12:00:00.123456Z")
+ end
+
+ it "leaves the timestamp it reads alone" do
+ expect { cursor_value }.not_to change { value.utc_offset }
+ end
+ end
+
+ context "with a date" do
+ let(:value) { Date.new(2026, 8, 3) }
+
+ it "writes it as an ISO 8601 date" do
+ expect(cursor_value).to eq("2026-08-03")
+ end
+ end
+
+ context "with a decimal" do
+ let(:value) { BigDecimal("1.5") }
+
+ it "writes it as a string" do
+ expect(cursor_value).to eq("1.5")
+ end
+ end
+
+ context "with a value no cursor can carry" do
+ let(:value) { { id: 1 } }
+
+ it "refuses the value" do
+ expect { cursor_value }.to raise_error(described_class::UnsupportedValue)
+ end
+ end
+
+ context "with a value a cursor already carries" do
+ let(:value) { described_class.coerce(Time.utc(2026, 8, 3, 12, 0, 0, 123_456)) }
+
+ it "returns it unchanged" do
+ expect(cursor_value).to eq("2026-08-03T12:00:00.123456Z")
+ end
+ end
+ end
+
+ describe ".valid?" do
+ subject { described_class }
+
+ let(:wire_cursor) { cursor.to_s }
+
+ it { is_expected.to be_valid(wire_cursor) }
+
+ context "when the string is no cursor" do
+ let(:wire_cursor) { "not base64!!" }
+
+ it { is_expected.not_to be_valid(wire_cursor) }
+ end
+ end
+
+ describe ".parse" do
+ subject(:parsed_cursor) { described_class.parse(wire_cursor) }
+
+ let(:wire_cursor) { cursor.to_s }
+
+ it "returns a cursor equal to the one that wrote the string" do
+ expect(parsed_cursor).to eq(cursor)
+ end
+
+ context "when the string is not base64" do
+ let(:wire_cursor) { "not base64!!" }
+
+ it "refuses the string" do
+ expect { parsed_cursor }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when the string holds no list of values" do
+ let(:wire_cursor) { Base64.urlsafe_encode64(%({"id":1}), padding: false) }
+
+ it "refuses the string" do
+ expect { parsed_cursor }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when the list holds another list" do
+ let(:wire_cursor) { Base64.urlsafe_encode64("[[1]]", padding: false) }
+
+ it "refuses the string" do
+ expect { parsed_cursor }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when the string is empty" do
+ let(:wire_cursor) { "" }
+
+ it "refuses the string" do
+ expect { parsed_cursor }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#to_s" do
+ subject(:written_cursor) { cursor.to_s }
+
+ it "writes the values as urlsafe base64 JSON" do
+ expect(written_cursor).to eq(Base64.urlsafe_encode64(%([42,"alice"]), padding: false))
+ end
+
+ context "when base64 would pad the string" do
+ let(:values) { [12] }
+
+ it "leaves the padding out" do
+ expect(written_cursor).not_to include("=")
+ end
+ end
+ end
+
+ describe "#==" do
+ let(:other_cursor) { described_class.new(values) }
+
+ context "when the other cursor holds the same values" do
+ it "equals the other cursor" do
+ expect(cursor).to eq(other_cursor)
+ end
+ end
+
+ context "when the other cursor holds other values" do
+ let(:other_cursor) { described_class.new([43, "alice"]) }
+
+ it "differs from the other cursor" do
+ expect(cursor).not_to eq(other_cursor)
+ end
+ end
+
+ context "when the other object is no cursor" do
+ let(:other_cursor) { "cursor-ish" }
+
+ it "differs from the other object" do
+ expect(cursor).not_to eq(other_cursor)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/direction_spec.rb b/spec/lib/json_api_kit/pagination/direction_spec.rb
new file mode 100644
index 00000000000..8d35ff1b60e
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/direction_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Direction do
+ subject(:direction) { described_class.for(declaration) }
+
+ let(:declaration) { :asc }
+
+ describe ".for" do
+ context "when nothing sorts in that direction" do
+ let(:declaration) { :sideways }
+
+ it "refuses the direction" do
+ expect { direction }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#to_sym" do
+ context "when the declaration is asc" do
+ it "returns asc" do
+ expect(direction.to_sym).to eq(:asc)
+ end
+ end
+
+ context "when the declaration is desc" do
+ let(:declaration) { :desc }
+
+ it "returns desc" do
+ expect(direction.to_sym).to eq(:desc)
+ end
+ end
+ end
+
+ describe "#to_sql" do
+ subject(:to_sql) { direction.to_sql }
+
+ context "when the direction sorts ascending" do
+ it "returns ASC" do
+ expect(to_sql).to eq("ASC")
+ end
+ end
+
+ context "when the direction sorts descending" do
+ let(:declaration) { :desc }
+
+ it "returns DESC" do
+ expect(to_sql).to eq("DESC")
+ end
+ end
+ end
+
+ describe "#operator" do
+ subject(:operator) { direction.operator }
+
+ context "when the direction sorts ascending" do
+ it "compares a later row as the greater one" do
+ expect(operator).to eq(">")
+ end
+ end
+
+ context "when the direction sorts descending" do
+ let(:declaration) { :desc }
+
+ it "compares a later row as the smaller one" do
+ expect(operator).to eq("<")
+ end
+ end
+ end
+
+ describe "#other_way" do
+ subject(:other_way) { direction.other_way }
+
+ context "when the direction sorts ascending" do
+ it "returns desc" do
+ expect(other_way).to eq(:desc)
+ end
+ end
+
+ context "when the direction sorts descending" do
+ let(:declaration) { :desc }
+
+ it "returns asc" do
+ expect(other_way).to eq(:asc)
+ end
+ end
+ end
+
+ describe "#nulls_first?" do
+ context "when the direction sorts ascending" do
+ it { is_expected.not_to be_nulls_first }
+ end
+
+ context "when the direction sorts descending" do
+ let(:declaration) { :desc }
+
+ it { is_expected.to be_nulls_first }
+ end
+ end
+
+ describe "#==" do
+ context "when the other direction sorts the same way" do
+ it "equals the other direction" do
+ expect(direction).to eq(described_class.for(:asc))
+ end
+
+ it "counts the two directions as one value" do
+ expect([described_class.for(:asc), described_class.for(:asc)].uniq).to contain_exactly(
+ direction,
+ )
+ end
+ end
+
+ context "when the other direction sorts the other way" do
+ it "differs from the other direction" do
+ expect(direction).not_to eq(described_class.for(:desc))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/keyset/key_spec.rb b/spec/lib/json_api_kit/pagination/keyset/key_spec.rb
new file mode 100644
index 00000000000..effb6e39842
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/keyset/key_spec.rb
@@ -0,0 +1,353 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Keyset::Key do
+ subject(:key) { described_class.new(:created_at, model:) }
+
+ let(:model) { Topic }
+
+ it { is_expected.to delegate_method(:operator).to(:direction) }
+ it { is_expected.to delegate_method(:trailing?).to(:nulls).with_prefix }
+ it { is_expected.to delegate_method(:read_first?).to(:nulls).with_prefix }
+
+ describe ".new" do
+ context "when the direction is unknown" do
+ it "refuses to build the key" do
+ expect { described_class.new(:created_at, model:, direction: :sideways) }.to raise_error(
+ ArgumentError,
+ )
+ end
+ end
+
+ context "when the nulls placement is unknown" do
+ it "refuses to build the key" do
+ expect { described_class.new(:bumped_at, model:, nulls: :middle) }.to raise_error(
+ ArgumentError,
+ )
+ end
+ end
+ end
+
+ describe "#nullable?" do
+ context "when the nulls placement is nil" do
+ it { is_expected.not_to be_nullable }
+ end
+
+ context "when the nulls placement is last" do
+ subject(:key) { described_class.new(:bumped_at, model:, nulls: :last) }
+
+ it { is_expected.to be_nullable }
+ end
+ end
+
+ describe "#direction" do
+ subject(:direction) { key.direction }
+
+ context "when there is no direction" do
+ it "sorts the key ascending" do
+ expect(direction.to_sym).to eq(:asc)
+ end
+ end
+ end
+
+ describe "#without_nulls" do
+ subject(:without_nulls) { key.without_nulls }
+
+ let(:key) { described_class.new(:bumped_at, model:, direction: :desc, nulls: :last) }
+
+ it "returns a key the database orders with no nulls placement" do
+ expect(without_nulls.ordering.to_s).to eq(%("topics"."bumped_at" DESC))
+ end
+
+ it "keeps the direction of the key" do
+ expect(without_nulls.direction.to_sym).to eq(:desc)
+ end
+ end
+
+ describe "#projected?" do
+ context "when the key carries no SQL" do
+ it { is_expected.not_to be_projected }
+ end
+
+ context "when the key carries its own SQL" do
+ subject(:key) { described_class.new(:username, model:, sql: "users.username") }
+
+ it { is_expected.to be_projected }
+ end
+ end
+
+ describe "#reverse" do
+ subject(:reversed_key) { key.reverse }
+
+ let(:key) do
+ described_class.new(
+ :username,
+ model:,
+ direction: :desc,
+ sql: "users.username",
+ joins: [:user],
+ )
+ end
+
+ it "reverses the direction" do
+ expect(reversed_key.direction.to_sym).to eq(:asc)
+ end
+
+ it "keeps the SQL of the key" do
+ expect(reversed_key.sql).to eq("users.username")
+ end
+
+ it "keeps the joins its SQL needs" do
+ expect(reversed_key.joins).to eq(JsonApiKit::Joins.for(:user))
+ end
+
+ context "when the key is nullable" do
+ let(:key) { described_class.new(:bumped_at, model:, nulls: :last) }
+
+ it { is_expected.to be_nullable }
+
+ it "moves the nulls to the other end" do
+ expect(reversed_key.ordering.to_s).to eq(%("topics"."bumped_at" DESC NULLS FIRST))
+ end
+ end
+ end
+
+ describe "#value_for" do
+ subject(:value) { key.value_for(record) }
+
+ let(:record) { Topic.new(created_at: Time.utc(2026, 8, 3, 12)) }
+
+ it "returns the value the key orders by" do
+ expect(value).to eq(Time.utc(2026, 8, 3, 12))
+ end
+ end
+
+ describe "#named?" do
+ it "matches its name as a symbol or a string" do
+ expect(key).to be_named(:created_at).and be_named("created_at")
+ end
+
+ it { is_expected.not_to be_named(:id) }
+ end
+
+ describe "#to_s" do
+ it "returns the name of the key" do
+ expect(key.to_s).to eq("created_at")
+ end
+ end
+
+ describe "#identifier" do
+ subject(:identifier) { key.identifier }
+
+ context "when the key carries no SQL" do
+ it "quotes the column and its table" do
+ expect(identifier).to eq(%("topics"."created_at"))
+ end
+ end
+
+ context "when the key carries its own SQL" do
+ let(:key) { described_class.new(:username, model:, sql: "users.username") }
+
+ it "quotes the name of the key, not its SQL" do
+ expect(identifier).to eq(%("topics"."username"))
+ end
+ end
+ end
+
+ describe "#value_sql" do
+ subject(:value_sql) { key.value_sql }
+
+ context "when the key carries no SQL" do
+ it "quotes the column and its table" do
+ expect(value_sql).to eq(%("topics"."created_at"))
+ end
+ end
+
+ context "when the key carries its own SQL" do
+ let(:key) { described_class.new(:username, model:, sql: "users.username") }
+
+ it "returns that SQL" do
+ expect(value_sql).to eq("users.username")
+ end
+ end
+ end
+
+ describe "#select_expression" do
+ subject(:select_expression) { key.select_expression }
+
+ context "when the key carries no SQL" do
+ it "returns nil" do
+ expect(select_expression).to be_nil
+ end
+ end
+
+ context "when the key carries its own SQL" do
+ let(:key) { described_class.new(:username, model:, sql: "users.username") }
+
+ it "projects the SQL under the name of the key" do
+ expect(select_expression).to eq(%(users.username AS "username"))
+ end
+ end
+ end
+
+ describe "#valued_condition" do
+ subject(:valued_ids) { key.valued_condition.call(scope).map(&:id) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+ fab!(:unpinned, :topic)
+
+ let(:key) { described_class.new(:pinned_at, model:, nulls: :last) }
+ let(:scope) { Topic.where(id: [pinned_topic.id, unpinned.id]) }
+
+ it "keeps the rows that hold a value for the key" do
+ expect(valued_ids).to contain_exactly(pinned_topic.id)
+ end
+
+ context "with a joined column" do
+ fab!(:section) { Fabricate(:category, name: "A section of the forum") }
+ fab!(:filed) { Fabricate(:topic, category: section) }
+ fab!(:unfiled, :private_message_topic)
+
+ let(:key) do
+ described_class.new(
+ :category_name,
+ model:,
+ sql: "categories.name",
+ joins: ["LEFT JOIN categories ON categories.id = topics.category_id"],
+ nulls: :last,
+ )
+ end
+ let(:scope) { Topic.where(id: [filed.id, unfiled.id]) }
+
+ it "joins its table" do
+ expect(valued_ids).to contain_exactly(filed.id)
+ end
+ end
+ end
+
+ describe "#null_condition" do
+ subject(:null_ids) { key.null_condition.call(scope).map(&:id) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+ fab!(:unpinned, :topic)
+
+ let(:key) { described_class.new(:pinned_at, model:, nulls: :last) }
+ let(:scope) { Topic.where(id: [pinned_topic.id, unpinned.id]) }
+
+ it "keeps the rows that hold no value for the key" do
+ expect(null_ids).to contain_exactly(unpinned.id)
+ end
+
+ context "with a joined column" do
+ fab!(:section) { Fabricate(:category, name: "A section of the forum") }
+ fab!(:filed) { Fabricate(:topic, category: section) }
+ fab!(:unfiled, :private_message_topic)
+
+ let(:key) do
+ described_class.new(
+ :category_name,
+ model:,
+ sql: "categories.name",
+ joins: ["LEFT JOIN categories ON categories.id = topics.category_id"],
+ nulls: :last,
+ )
+ end
+ let(:scope) { Topic.where(id: [filed.id, unfiled.id]) }
+
+ it "joins its table" do
+ expect(null_ids).to contain_exactly(unfiled.id)
+ end
+ end
+ end
+
+ describe "#at_or_after" do
+ subject(:kept_ids) { key.at_or_after(scope, Time.utc(2026, 8, 2)).map(&:id) }
+
+ fab!(:older) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
+ fab!(:newer) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+
+ let(:scope) { Topic.where(id: [older.id, newer.id]) }
+
+ context "when the key sorts ascending" do
+ it "keeps the rows at or after the value" do
+ expect(kept_ids).to contain_exactly(newer.id)
+ end
+ end
+
+ context "when the key sorts descending" do
+ let(:key) { described_class.new(:created_at, model:, direction: :desc) }
+
+ it "keeps the rows at or before the value" do
+ expect(kept_ids).to contain_exactly(older.id)
+ end
+ end
+
+ context "when the key carries its own SQL" do
+ subject(:kept_ids) { key.at_or_after(scope, "b").map(&:id) }
+
+ fab!(:alice_topic) { Fabricate(:topic, user: Fabricate(:user, username: "alice")) }
+ fab!(:carol_topic) { Fabricate(:topic, user: Fabricate(:user, username: "carol")) }
+
+ let(:key) { described_class.new(:author, model:, sql: "users.username", joins: [:user]) }
+ let(:scope) { Topic.where(id: [alice_topic.id, carol_topic.id]).joins(:user) }
+
+ it "compares the SQL and not the column" do
+ expect(kept_ids).to contain_exactly(carol_topic.id)
+ end
+ end
+ end
+
+ describe "#cast" do
+ subject(:cast) { key.cast(value) }
+
+ let(:value) { "2026-08-03T12:00:00.123456Z" }
+
+ context "when the column holds a timestamp" do
+ it "returns a time, to the microsecond" do
+ expect(cast).to eq(Time.utc(2026, 8, 3, 12, 0, 0, 123_456))
+ end
+ end
+
+ context "when the column holds an integer" do
+ let(:key) { described_class.new(:id, model:) }
+ let(:value) { "12" }
+
+ it "returns an integer" do
+ expect(cast).to be(12)
+ end
+ end
+
+ context "when the model has no column of that name" do
+ let(:key) { described_class.new(:username, model:, sql: "users.username") }
+
+ it "returns the value with no change" do
+ expect(cast).to eq("2026-08-03T12:00:00.123456Z")
+ end
+ end
+ end
+
+ describe "#ordering" do
+ subject(:ordering) { key.ordering.to_s }
+
+ context "when the key sorts ascending" do
+ it "orders by the column, ascending" do
+ expect(ordering).to eq(%("topics"."created_at" ASC))
+ end
+ end
+
+ context "when the key sorts descending" do
+ let(:key) { described_class.new(:created_at, model:, direction: :desc) }
+
+ it "orders by the column, descending" do
+ expect(ordering).to eq(%("topics"."created_at" DESC))
+ end
+ end
+
+ context "when the nulls placement is last" do
+ let(:key) { described_class.new(:bumped_at, model:, direction: :desc, nulls: :last) }
+
+ it "orders the nulls at that end" do
+ expect(ordering).to eq(%("topics"."bumped_at" DESC NULLS LAST))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/keyset_spec.rb b/spec/lib/json_api_kit/pagination/keyset_spec.rb
new file mode 100644
index 00000000000..e5b1beebefb
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/keyset_spec.rb
@@ -0,0 +1,228 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Keyset do
+ subject(:keyset) { described_class.new(keys) }
+
+ let(:model) { Topic }
+ let(:keys) do
+ [
+ described_class::Key.new(:created_at, model:, direction: :desc),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it { is_expected.to delegate_method(:valued_condition).to(:leading) }
+ it { is_expected.to delegate_method(:null_condition).to(:leading) }
+ it { is_expected.to delegate_method(:nulls_read_first?).to(:leading) }
+
+ describe ".new" do
+ context "when there is no key" do
+ let(:keys) { [] }
+
+ it "refuses to build the keyset" do
+ expect { keyset }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when the same key appears twice" do
+ let(:keys) do
+ [
+ described_class::Key.new(:id, model:, direction: :desc),
+ described_class::Key.new(:created_at, model:),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it "keeps the first of the two" do
+ expect(keyset.keys).to eq(keys.take(2))
+ end
+ end
+ end
+
+ describe "#leading" do
+ subject(:leading) { keyset.leading }
+
+ it "returns the key the listing reads first" do
+ expect(leading.name).to eq(:created_at)
+ end
+ end
+
+ describe "#rest" do
+ subject(:rest) { keyset.rest }
+
+ it "returns the keyset behind the leading key" do
+ expect(rest.keys.map(&:name)).to eq([:id])
+ end
+
+ context "when no key follows the leading key" do
+ let(:keys) { [described_class::Key.new(:created_at, model:)] }
+
+ it "refuses to build the keyset" do
+ expect { rest }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#split?" do
+ context "when the leading key cannot be null" do
+ it { is_expected.not_to be_split }
+ end
+
+ context "when the leading key can be null" do
+ let(:keys) do
+ [
+ described_class::Key.new(:bumped_at, model:, nulls: :last),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it { is_expected.to be_split }
+ end
+ end
+
+ describe "#without_nulls" do
+ subject(:without_nulls) { keyset.without_nulls }
+
+ let(:keys) do
+ [
+ described_class::Key.new(:bumped_at, model:, direction: :desc, nulls: :last),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it "returns a keyset whose leading key cannot be null" do
+ expect(without_nulls.leading).not_to be_nullable
+ end
+
+ it "keeps the keys behind the leading one" do
+ expect(without_nulls.keys.drop(1)).to eq(keys.drop(1))
+ end
+ end
+
+ describe "#columns" do
+ subject(:columns) { keyset.columns }
+
+ it "returns the column every key reads" do
+ expect(columns).to eq(%i[created_at id])
+ end
+
+ context "when a key carries its own SQL" do
+ let(:keys) do
+ [
+ described_class::Key.new(:author, model:, sql: "users.username", joins: [:user]),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it "leaves that key out" do
+ expect(columns).to eq([:id])
+ end
+ end
+ end
+
+ describe "#order" do
+ before { keys.each { allow(it).to receive(:ordering).and_return("#{it.name} ordering") } }
+
+ it "orders by every key, in sequence" do
+ expect(keyset.order).to eq(["created_at ordering", "id ordering"])
+ end
+ end
+
+ describe "#values_for" do
+ subject(:values) { keyset.values_for(record) }
+
+ let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3, 12)) }
+
+ it "returns one value for each key, in the form a cursor carries" do
+ expect(values).to eql(["2026-08-03T12:00:00.000000Z", 12])
+ end
+ end
+
+ describe "#joins" do
+ subject(:joins) { keyset.joins }
+
+ let(:keys) do
+ [
+ described_class::Key.new(:username, model:, sql: "users.username", joins: [:user]),
+ described_class::Key.new(:title, model:, sql: "topics.title", joins: [:user]),
+ ]
+ end
+
+ it "returns each join once" do
+ expect(joins).to eq(JsonApiKit::Joins.for(:user))
+ end
+ end
+
+ describe "#reverse" do
+ let(:keys) do
+ [
+ described_class::Key.new(:bumped_at, model:, direction: :desc, nulls: :last),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ before { keys.each { allow(it).to receive(:reverse).and_call_original } }
+
+ it "reverses every one of its keys" do
+ keyset.reverse
+
+ expect(keys).to all(have_received(:reverse))
+ end
+ end
+
+ describe "#compatible_with?" do
+ let(:values) { ["2026-08-03T12:00:00.000000Z", 12] }
+
+ it "accepts one value for each key" do
+ expect(keyset).to be_compatible_with(values)
+ end
+
+ context "when there are fewer values than the keyset compares" do
+ let(:values) { [12] }
+
+ it "refuses them" do
+ expect(keyset).not_to be_compatible_with(values)
+ end
+ end
+ end
+
+ describe "#project" do
+ subject(:projected_scope) { keyset.project(scope) }
+
+ fab!(:topic)
+
+ let(:scope) { Topic.where(id: topic.id) }
+
+ context "when no key carries its own SQL" do
+ it "returns the same scope" do
+ expect(projected_scope).to be(scope)
+ end
+ end
+
+ context "when a key carries its own SQL" do
+ let(:keys) do
+ [
+ described_class::Key.new(:author, model:, sql: "users.username", joins: [:user]),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it "reads the value of that SQL under the name of the key" do
+ expect(projected_scope.first.author).to eq(topic.user.username)
+ end
+ end
+
+ context "when a key is nullable" do
+ let(:keys) do
+ [
+ described_class::Key.new(:bumped_at, model:, direction: :desc, nulls: :last),
+ described_class::Key.new(:id, model:),
+ ]
+ end
+
+ it "returns the same scope" do
+ expect(projected_scope).to be(scope)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/nulls_spec.rb b/spec/lib/json_api_kit/pagination/nulls_spec.rb
new file mode 100644
index 00000000000..e7c0e6f62c4
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/nulls_spec.rb
@@ -0,0 +1,142 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Nulls do
+ subject(:nulls) { described_class.for(placement, direction:) }
+
+ let(:placement) { :last }
+ let(:direction) { JsonApiKit::Pagination::Direction.for(:asc) }
+
+ describe ".for" do
+ context "when nulls cannot sort at that placement" do
+ let(:placement) { :middle }
+
+ it "refuses the placement" do
+ expect { nulls }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#expected?" do
+ context "when the placement is last" do
+ it { is_expected.to be_expected }
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ it { is_expected.not_to be_expected }
+ end
+ end
+
+ describe "#placement" do
+ context "when the placement is last" do
+ it "returns last" do
+ expect(nulls.placement).to eq(:last)
+ end
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ it "returns nil" do
+ expect(nulls.placement).to be_nil
+ end
+ end
+ end
+
+ describe "#to_sql" do
+ subject(:to_sql) { nulls.to_sql }
+
+ context "when the placement is last" do
+ it "orders the nulls at the end" do
+ expect(to_sql).to eq(" NULLS LAST")
+ end
+ end
+
+ context "when the placement is first" do
+ let(:placement) { :first }
+
+ it "orders the nulls at the start" do
+ expect(to_sql).to eq(" NULLS FIRST")
+ end
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ it "adds nothing, and the database places the nulls" do
+ expect(to_sql).to eq("")
+ end
+ end
+ end
+
+ describe "#other_end" do
+ subject(:other_end) { nulls.other_end }
+
+ context "when the placement is last" do
+ it "returns first" do
+ expect(other_end).to eq(:first)
+ end
+ end
+
+ context "when the placement is first" do
+ let(:placement) { :first }
+
+ it "returns last" do
+ expect(other_end).to eq(:last)
+ end
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ it "returns nil" do
+ expect(other_end).to be_nil
+ end
+ end
+ end
+
+ describe "#trailing?" do
+ context "when the placement is last" do
+ it { is_expected.to be_trailing }
+ end
+
+ context "when the placement is first" do
+ let(:placement) { :first }
+
+ it { is_expected.not_to be_trailing }
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ it { is_expected.not_to be_trailing }
+ end
+ end
+
+ describe "#read_first?" do
+ context "when the placement is last" do
+ it { is_expected.not_to be_read_first }
+ end
+
+ context "when the placement is first" do
+ let(:placement) { :first }
+
+ it { is_expected.to be_read_first }
+ end
+
+ context "when the placement is nil" do
+ let(:placement) { nil }
+
+ context "when the direction sorts ascending" do
+ it { is_expected.not_to be_read_first }
+ end
+
+ context "when the direction sorts descending" do
+ let(:direction) { JsonApiKit::Pagination::Direction.for(:desc) }
+
+ it { is_expected.to be_read_first }
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/numbered_rows_spec.rb b/spec/lib/json_api_kit/pagination/numbered_rows_spec.rb
new file mode 100644
index 00000000000..154ff01c347
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/numbered_rows_spec.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::NumberedRows do
+ subject(:numbered_rows) { described_class.new(scope, owner_key: :topic_id, keyset:, size:) }
+
+ fab!(:topic)
+ fab!(:other_topic, :topic)
+ fab!(:posts) { 3.times.map { Fabricate(:post, topic:) } }
+ fab!(:other_posts) { 3.times.map { Fabricate(:post, topic: other_topic) } }
+
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:post_number, model: Post), key.new(:id, model: Post)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:scope) { Post.where(topic_id: [topic.id, other_topic.id]) }
+ let(:size) { 1 }
+
+ describe "#bounded_scope" do
+ subject(:records) { numbered_rows.bounded_scope.to_a }
+
+ let(:post_numbers) do
+ records.group_by(&:topic_id).transform_values { it.map(&:post_number).sort }
+ end
+
+ it "reads one row more than the page holds, for each owner" do
+ expect(post_numbers).to eq(topic.id => [1, 2], other_topic.id => [1, 2])
+ end
+
+ it "leaves the row number out of the rows it reads" do
+ expect(records.first.attributes).not_to have_key(described_class::ROW_NUMBER)
+ end
+
+ context "when the scope selects two columns" do
+ let(:scope) { Post.where(topic_id: [topic.id, other_topic.id]).select(:id, :topic_id) }
+
+ it "reads those columns only" do
+ expect(records.first.attributes.keys).to eq(%w[id topic_id])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/order/position_spec.rb b/spec/lib/json_api_kit/pagination/order/position_spec.rb
new file mode 100644
index 00000000000..d9ceff8f1f2
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/order/position_spec.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Order::Position do
+ subject(:position) { described_class.new(segment:, values:) }
+
+ fab!(:topic)
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:order) { JsonApiKit::Pagination::Order.new(keyset) }
+ let(:segment) { order.fetch(1) }
+ let(:values) { [topic.id] }
+
+ describe ".from" do
+ subject(:position) { described_class.from(cursor, order:) }
+
+ let(:cursor) { JsonApiKit::Pagination::Cursor.new([order.digest, 1, topic.id]) }
+
+ it "returns a position in the segment the cursor names" do
+ expect(position.segment).to eq(order.fetch(1))
+ end
+
+ it "keeps the values of the cursor" do
+ expect(position.values).to eq([topic.id])
+ end
+ end
+
+ describe ".new" do
+ context "with fewer values than the segment compares" do
+ let(:values) { [] }
+
+ it "refuses them" do
+ expect { position }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "with more values than the segment compares" do
+ let(:values) { [topic.pinned_at, topic.id] }
+
+ it "refuses them" do
+ expect { position }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#to_cursor" do
+ it "returns a cursor that starts with the listing and the segment" do
+ expect(position.to_cursor.values).to eq([order.digest, 1, topic.id])
+ end
+ end
+
+ describe "#in" do
+ subject(:in_reverse) { position.in(order.reverse) }
+
+ it "keeps the same segment id" do
+ expect(in_reverse.segment.id).to eq(segment.id)
+ end
+
+ it "takes the directions of the other order" do
+ expect(in_reverse.segment.keyset.keys.map { it.direction.to_sym }).to eq([:desc])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/order/segment_spec.rb b/spec/lib/json_api_kit/pagination/order/segment_spec.rb
new file mode 100644
index 00000000000..baef24da7e5
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/order/segment_spec.rb
@@ -0,0 +1,199 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Order::Segment do
+ subject(:segment) { described_class.new(id: 1, keyset:, condition:) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+ fab!(:unpinned_topic, :topic)
+ fab!(:other_unpinned, :topic)
+
+ let(:model) { Topic }
+ let(:keyset) do
+ JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)])
+ end
+ let(:condition) { ->(scope) { scope.where(pinned_at: nil) } }
+ let(:scope) { Topic.where(id: [pinned_topic.id, unpinned_topic.id, other_unpinned.id]) }
+
+ it { is_expected.to delegate_method(:columns).to(:keyset) }
+ it { is_expected.to delegate_method(:compatible_with?).to(:keyset) }
+
+ describe ".split" do
+ subject(:segments) { described_class.split(keyset) }
+
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:created_at, model:, direction: :desc), key.new(:id, model:)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:unpinned_ids) { [unpinned_topic.id, other_unpinned.id] }
+
+ context "when the leading key cannot be null" do
+ it "returns one segment" do
+ expect(segments.size).to eq(1)
+ end
+
+ it "gives that segment every row of the listing" do
+ expect(segments.first.scope(scope)).to be(scope)
+ end
+ end
+
+ context "when the leading key can be null" do
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)]
+ end
+
+ it "returns two segments" do
+ expect(segments.map(&:id)).to eq([0, 1])
+ end
+
+ it "gives the first segment the rows that hold a value" do
+ expect(segments.first.scope(scope).map(&:id)).to contain_exactly(pinned_topic.id)
+ end
+
+ it "gives the second segment the rows that hold none" do
+ expect(segments.last.scope(scope).map(&:id)).to match_array(unpinned_ids)
+ end
+
+ it "orders the first segment by that key then by id" do
+ expect(segments.first.keyset.keys.map(&:name)).to eq(%i[pinned_at id])
+ end
+
+ it "drops that key from the second segment" do
+ expect(segments.last.keyset.keys.map(&:name)).to eq([:id])
+ end
+
+ it "orders the first segment with no nulls placement" do
+ expect(segments.first.keyset.order.join(" ")).not_to include("NULLS")
+ end
+ end
+
+ context "when the leading key sorts its nulls first" do
+ let(:keys) { [key.new(:pinned_at, model:, nulls: :first), key.new(:id, model:)] }
+
+ it "puts the segment that holds the null rows first" do
+ expect(segments.first.scope(scope).map(&:id)).to match_array(unpinned_ids)
+ end
+ end
+
+ context "when no key follows a nullable key" do
+ let(:keys) { [key.new(:pinned_at, model:, nulls: :last)] }
+
+ it "refuses to split the keyset" do
+ expect { segments }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when a nullable key does not lead" do
+ let(:keys) { [key.new(:created_at, model:), key.new(:pinned_at, model:, nulls: :last)] }
+
+ it "returns one segment" do
+ expect(segments.size).to eq(1)
+ end
+ end
+
+ context "when two nullable keys lead" do
+ let(:keys) do
+ [
+ key.new(:pinned_at, model:, nulls: :last),
+ key.new(:bumped_at, model:, nulls: :last),
+ key.new(:id, model:),
+ ]
+ end
+
+ it "returns three segments" do
+ expect(segments.size).to eq(3)
+ end
+
+ it "drops one more key from each segment" do
+ expect(segments.map { it.keyset.keys.map(&:name) }).to eq(
+ [%i[pinned_at bumped_at id], %i[bumped_at id], %i[id]],
+ )
+ end
+ end
+ end
+
+ describe "#scope" do
+ subject(:segment_ids) { segment.scope(scope) }
+
+ it "returns only the rows the segment holds" do
+ expect(segment_ids.map(&:id)).to contain_exactly(unpinned_topic.id, other_unpinned.id)
+ end
+
+ context "when the segment holds every row of the listing" do
+ let(:condition) { described_class::NO_CONDITION }
+
+ it "returns the same scope" do
+ expect(segment_ids).to be(scope)
+ end
+ end
+ end
+
+ describe "#narrowed_by" do
+ subject(:segment_ids) { segment.narrowed_by(other).scope(scope).map(&:id) }
+
+ let(:other) { ->(scope) { scope.where(id: [pinned_topic.id, unpinned_topic.id]) } }
+
+ it "returns the rows that both conditions keep" do
+ expect(segment_ids).to contain_exactly(unpinned_topic.id)
+ end
+
+ context "when the other condition keeps rows the segment does not hold" do
+ let(:other) { ->(scope) { scope.where(id: pinned_topic.id) } }
+
+ it "returns no row" do
+ expect(segment_ids).to be_empty
+ end
+ end
+ end
+
+ describe "#position_of" do
+ subject(:position) { segment.position_of(record) }
+
+ let(:record) { unpinned_topic }
+
+ it "places the row in this segment" do
+ expect(position.segment).to eq(segment)
+ end
+
+ it "carries the values this segment compares" do
+ expect(position.values).to eq(keyset.values_for(record))
+ end
+
+ context "when the segment compares a timestamp" do
+ let(:keyset) do
+ JsonApiKit::Pagination::Keyset.new(
+ [JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:)],
+ )
+ end
+ let(:record) { Topic.new(created_at: Time.utc(2026, 8, 3, 12, 0, 0, 123_456)) }
+ let(:cursor) { position.to_cursor }
+
+ it "writes a cursor that reads back the same values" do
+ expect(JsonApiKit::Pagination::Cursor.parse(cursor.to_s)).to eq(cursor)
+ end
+ end
+ end
+
+ describe "#led_by?" do
+ it { is_expected.to be_led_by(:id) }
+
+ it { is_expected.not_to be_led_by(:created_at) }
+ end
+
+ describe "#reverse" do
+ subject(:reversed_segment) { segment.reverse }
+
+ it "keeps its id" do
+ expect(reversed_segment.id).to eq(1)
+ end
+
+ it "keeps the rows it holds" do
+ expect(reversed_segment.scope(scope).map(&:id)).to contain_exactly(
+ unpinned_topic.id,
+ other_unpinned.id,
+ )
+ end
+
+ it "reads its keyset the other way" do
+ expect(reversed_segment.keyset.keys.map { it.direction.to_sym }).to eq([:desc])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/order/segments_spec.rb b/spec/lib/json_api_kit/pagination/order/segments_spec.rb
new file mode 100644
index 00000000000..8ed06745714
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/order/segments_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Order::Segments do
+ subject(:segments) { described_class.for(keyset) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+ fab!(:unpinned_topic, :topic)
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:pinned_at, model:, direction: :asc, nulls: :last), key.new(:id, model:)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:scope) { Topic.where(id: [pinned_topic.id, unpinned_topic.id]) }
+
+ describe "#fetch" do
+ it "returns the segment with that id" do
+ expect(segments.fetch(1)).to eq(segments.last)
+ end
+
+ context "when no segment has that id" do
+ it "refuses the id" do
+ expect { segments.fetch(9) }.to raise_error(KeyError)
+ end
+ end
+ end
+
+ describe "#after" do
+ subject(:later_segments) { segments.after(segments.first) }
+
+ it "returns the segments that follow it" do
+ expect(later_segments.map(&:id)).to eq([1])
+ end
+
+ context "when no segment follows it" do
+ subject(:later_segments) { segments.after(segments.last) }
+
+ it { is_expected.to be_empty }
+ end
+ end
+
+ describe "#after_every_value_of" do
+ it "returns the segments after the one that holds values for the key" do
+ expect(segments.after_every_value_of(:pinned_at).map(&:id)).to eq([1])
+ end
+ end
+
+ describe "#locate" do
+ let(:located_row) { segments.locate(rows) }
+ let(:rows) { scope }
+
+ it "returns the first row the listing reads" do
+ expect(located_row.record).to eq(pinned_topic)
+ end
+
+ it "places the row in the segment that holds it" do
+ expect(located_row.position.segment).to eq(segments.first)
+ end
+
+ context "when only a later segment holds a row" do
+ let(:rows) { scope.where(id: unpinned_topic.id) }
+
+ it "places the row in that segment" do
+ expect(located_row.position.segment).to eq(segments.last)
+ end
+ end
+
+ context "when no segment holds a row" do
+ let(:rows) { scope.where(id: -1) }
+
+ it "returns nil" do
+ expect(located_row).to be_nil
+ end
+ end
+ end
+
+ describe "#columns" do
+ it "returns the columns of every segment, each one once" do
+ expect(segments.columns).to eq(%i[pinned_at id])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/order_spec.rb b/spec/lib/json_api_kit/pagination/order_spec.rb
new file mode 100644
index 00000000000..a1a058aaa57
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/order_spec.rb
@@ -0,0 +1,129 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Order do
+ subject(:order) { described_class.new(keyset) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+ fab!(:unpinned_topic, :topic)
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:created_at, model:, direction: :desc), key.new(:id, model:)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:scope) { Topic.where(id: [pinned_topic.id, unpinned_topic.id]) }
+
+ it { is_expected.to delegate_method(:leading).to(:keyset) }
+ it { is_expected.to delegate_method(:first).to(:segments) }
+ it { is_expected.to delegate_method(:columns).to(:segments) }
+ it { is_expected.to delegate_method(:locate).to(:segments) }
+ it { is_expected.to delegate_method(:fetch).to(:segments) }
+ it { is_expected.to delegate_method(:after).to(:segments) }
+
+ describe "#compatible_with?" do
+ let(:cursor) do
+ JsonApiKit::Pagination::Cursor.new(
+ [order.digest, 0, pinned_topic.created_at, pinned_topic.id],
+ )
+ end
+
+ it "accepts the cursor" do
+ expect(order).to be_compatible_with(cursor:)
+ end
+
+ context "when no segment of this order has that id" do
+ let(:cursor) do
+ JsonApiKit::Pagination::Cursor.new([order.digest, 7, pinned_topic.created_at, 1])
+ end
+
+ it "refuses the cursor" do
+ expect(order).not_to be_compatible_with(cursor:)
+ end
+ end
+
+ context "when the cursor holds another number of values" do
+ let(:cursor) { JsonApiKit::Pagination::Cursor.new([order.digest, 0, pinned_topic.id]) }
+
+ it "refuses the cursor" do
+ expect(order).not_to be_compatible_with(cursor:)
+ end
+ end
+ end
+
+ describe "#split?" do
+ context "when the leading key cannot be null" do
+ it { is_expected.not_to be_split }
+ end
+
+ context "when the leading key can be null" do
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)]
+ end
+
+ it { is_expected.to be_split }
+ end
+ end
+
+ describe "#reverse" do
+ subject(:reversed_order) { order.reverse }
+
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)]
+ end
+
+ it "reads its segments in the other sequence" do
+ expect(reversed_order.segments.map(&:id)).to eq([1, 0])
+ end
+
+ it "keeps each segment id on the rows it holds" do
+ expect(reversed_order.first.scope(scope).map(&:id)).to contain_exactly(unpinned_topic.id)
+ end
+ end
+
+ describe "#enter" do
+ subject(:entry_row) { order.enter(scope, at_or_after:) }
+
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :asc, nulls: :last), key.new(:id, model:)]
+ end
+ let(:at_or_after) { scope.where("pinned_at >= ?", Time.utc(2026, 7, 1)) }
+
+ it "returns the first row at or after the value" do
+ expect(entry_row.record).to eq(pinned_topic)
+ end
+
+ context "when no row holds a value for that key" do
+ let(:at_or_after) { scope.where("pinned_at >= ?", Time.utc(2030, 1, 1)) }
+
+ it "returns the first row of a later segment" do
+ expect(entry_row.record).to eq(unpinned_topic)
+ end
+
+ it "places the row in that segment" do
+ expect(entry_row.position.segment).to eq(order.segments.last)
+ end
+ end
+
+ context "when the listing holds no row" do
+ let(:scope) { Topic.where(id: -1) }
+
+ it "returns nil" do
+ expect(entry_row).to be_nil
+ end
+ end
+ end
+
+ describe "#position" do
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)]
+ end
+ let(:cursor) { JsonApiKit::Pagination::Cursor.new([order.digest, 1, unpinned_topic.id]) }
+
+ before { allow(JsonApiKit::Pagination::Order::Position).to receive(:from) }
+
+ it "places the cursor in this order" do
+ order.position(cursor)
+
+ expect(JsonApiKit::Pagination::Order::Position).to have_received(:from).with(cursor, order:)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/page_per_owner_spec.rb b/spec/lib/json_api_kit/pagination/page_per_owner_spec.rb
new file mode 100644
index 00000000000..800b0ee4e4c
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/page_per_owner_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::PagePerOwner do
+ subject(:page) { described_class.new(scope, order:, size: 2, owner_key: :topic_id) }
+
+ fab!(:topic)
+ fab!(:posts) { 3.times.map { Fabricate(:post, topic:) } }
+
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:post_number, model: Post), key.new(:id, model: Post)] }
+ let(:order) { JsonApiKit::Pagination::Order.new(JsonApiKit::Pagination::Keyset.new(keys)) }
+ let(:scope) { Post.where(topic_id: topic.id) }
+
+ describe ".new" do
+ context "when the leading key can be null" do
+ let(:keys) { [key.new(:deleted_at, model: Post, nulls: :last), key.new(:id, model: Post)] }
+
+ it "refuses the order" do
+ expect { page }.to raise_error(described_class::SplitOrder)
+ end
+ end
+ end
+
+ describe "#rows" do
+ it "reads one row more than the page holds" do
+ expect(page.rows.map(&:record)).to eq(posts)
+ end
+
+ it "reads the rows in the order of the listing" do
+ expect(page.rows.map { it.record.post_number }).to eq([1, 2, 3])
+ end
+ end
+
+ describe "#next" do
+ it "returns no cursor" do
+ expect(page.next).to be_nil
+ end
+ end
+
+ describe "#previous" do
+ it "returns no cursor" do
+ expect(page.previous).to be_nil
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/paginator_spec.rb b/spec/lib/json_api_kit/pagination/paginator_spec.rb
new file mode 100644
index 00000000000..8d0ca1f3d32
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/paginator_spec.rb
@@ -0,0 +1,155 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Paginator do
+ subject(:paginator) { described_class.for(scope, order:, size:, after:, before:) }
+
+ fab!(:first_topic, :topic)
+ fab!(:second_topic, :topic)
+ fab!(:third_topic, :topic)
+ fab!(:fourth_topic, :topic)
+ fab!(:fifth_topic, :topic)
+
+ let(:model) { Topic }
+ let(:topics) { [first_topic, second_topic, third_topic, fourth_topic, fifth_topic] }
+ let(:order) do
+ JsonApiKit::Pagination::Order.new(
+ JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)]),
+ )
+ end
+ let(:scope) { Topic.where(id: topics.map(&:id)) }
+ let(:first_cursor) { order.first.position_of(first_topic).to_cursor }
+ let(:second_cursor) { order.first.position_of(second_topic).to_cursor }
+ let(:third_cursor) { order.first.position_of(third_topic).to_cursor }
+ let(:fourth_cursor) { order.first.position_of(fourth_topic).to_cursor }
+ let(:fifth_cursor) { order.first.position_of(fifth_topic).to_cursor }
+ let(:size) { 2 }
+ let(:after) { nil }
+ let(:before) { nil }
+
+ describe ".for" do
+ it "returns a paginator that reads forwards" do
+ expect(paginator).to be_an_instance_of(described_class::Forwards)
+ end
+
+ context "when there is an after cursor" do
+ let(:after) { second_cursor }
+
+ it "returns a paginator that reads forwards from it" do
+ expect(paginator).to be_an_instance_of(described_class::Forwards)
+ end
+ end
+
+ context "when there is a before cursor" do
+ let(:before) { fourth_cursor }
+
+ it "returns a paginator that reads backwards from it" do
+ expect(paginator).to be_an_instance_of(described_class::Backwards)
+ end
+ end
+
+ context "when there is a cursor at both ends" do
+ let(:after) { first_cursor }
+ let(:before) { fourth_cursor }
+
+ it "refuses the request" do
+ expect { paginator }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#rows" do
+ subject(:rows) { paginator.rows }
+
+ it "reads the first rows of the listing" do
+ expect(rows.map(&:record)).to eq([first_topic, second_topic])
+ end
+
+ context "when there is a before cursor" do
+ let(:before) { fifth_cursor }
+
+ it "reads the page before it, in the order of the listing" do
+ expect(rows.map(&:record)).to eq([third_topic, fourth_topic])
+ end
+ end
+ end
+
+ describe "#next" do
+ subject(:next_page) { paginator.next }
+
+ it "returns the cursor of the last row of the page" do
+ expect(next_page).to eq(second_cursor)
+ end
+
+ context "when the page ends on the last row of the listing" do
+ let(:after) { third_cursor }
+
+ it "returns no cursor" do
+ expect(next_page).to be_nil
+ end
+ end
+
+ context "when the cursor sits on the last row" do
+ let(:after) { fifth_cursor }
+
+ it "returns no cursor" do
+ expect(next_page).to be_nil
+ end
+ end
+
+ context "when the page reads backwards" do
+ let(:before) { fifth_cursor }
+
+ it "returns the cursor of the last row of the page" do
+ expect(next_page).to eq(fourth_cursor)
+ end
+ end
+
+ context "when the page reads backwards past the first row of the listing" do
+ let(:before) { first_cursor }
+
+ it "returns the cursor it starts from" do
+ expect(next_page).to eq(first_cursor)
+ end
+ end
+ end
+
+ describe "#previous" do
+ subject(:previous_page) { paginator.previous }
+
+ it "returns no cursor" do
+ expect(previous_page).to be_nil
+ end
+
+ context "when there is an after cursor" do
+ let(:after) { second_cursor }
+
+ it "returns the cursor of the first row of the page" do
+ expect(previous_page).to eq(third_cursor)
+ end
+ end
+
+ context "when the cursor sits on the last row" do
+ let(:after) { fifth_cursor }
+
+ it "returns the cursor it starts from" do
+ expect(previous_page).to eq(fifth_cursor)
+ end
+ end
+
+ context "when the page reads backwards" do
+ let(:before) { fifth_cursor }
+
+ it "returns the cursor of the first row of the page" do
+ expect(previous_page).to eq(third_cursor)
+ end
+ end
+
+ context "when the page reads backwards to the first row of the listing" do
+ let(:before) { third_cursor }
+
+ it "returns no cursor" do
+ expect(previous_page).to be_nil
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb b/spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb
new file mode 100644
index 00000000000..3e4ab4d7aa5
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Predicate::Term::Null do
+ subject(:term) { described_class.new(key) }
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:bumped_at, model:) }
+
+ describe "#comparable?" do
+ it { is_expected.not_to be_comparable }
+ end
+
+ describe "#matches" do
+ subject(:matches) { term.matches }
+
+ it "matches a row that holds null" do
+ expect(matches).to eq(%("topics"."bumped_at" IS NULL))
+ end
+ end
+
+ describe "#disjuncts" do
+ subject(:disjuncts) { term.disjuncts([]) }
+
+ context "when the order reads the nulls last" do
+ it "returns no comparison" do
+ expect(disjuncts).to be_empty
+ end
+ end
+
+ context "when the order reads the nulls first" do
+ let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:bumped_at, model:, nulls: :first) }
+
+ it "returns one comparison for the rows that hold a value" do
+ expect(disjuncts).to eq([%(("topics"."bumped_at" IS NOT NULL))])
+ end
+ end
+ end
+
+ describe "#bound_on" do
+ subject(:bounded_comparison) { term.bound_on("THE COMPARISON") }
+
+ it "adds no bound to the comparison" do
+ expect(bounded_comparison).to eq("THE COMPARISON")
+ end
+ end
+
+ describe "#bindings" do
+ subject(:bindings) { term.bindings }
+
+ it "binds no value" do
+ expect(bindings).to be_empty
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/predicate/term_spec.rb b/spec/lib/json_api_kit/pagination/predicate/term_spec.rb
new file mode 100644
index 00000000000..1c0423cbeab
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/predicate/term_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Predicate::Term do
+ subject(:term) { described_class.for(key, value) }
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:) }
+ let(:descending_key) do
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:, direction: :desc)
+ end
+ let(:value) { "2026-08-03T12:00:00.123456Z" }
+
+ describe ".for" do
+ it "returns a term that compares the value" do
+ expect(term).to be_an_instance_of(described_class)
+ end
+
+ context "when the cursor holds no value for the key" do
+ let(:value) { nil }
+
+ it "returns a term that compares nothing" do
+ expect(term).to be_an_instance_of(described_class::Null)
+ end
+ end
+
+ context "when the cursor holds false for the key" do
+ let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:closed, model:) }
+ let(:value) { false }
+
+ it "returns a term that compares the false value" do
+ expect(term).to be_an_instance_of(described_class)
+ end
+ end
+ end
+
+ describe "#comparable?" do
+ it { is_expected.to be_comparable }
+
+ context "when the key sorts its nulls last" do
+ let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:pinned_at, model:, nulls: :last) }
+
+ it { is_expected.not_to be_comparable }
+ end
+ end
+
+ describe "#placeholder" do
+ subject(:placeholder) { term.placeholder }
+
+ it "returns the key name as the placeholder" do
+ expect(placeholder).to eq(":created_at")
+ end
+ end
+
+ describe "#matches" do
+ subject(:matches) { term.matches }
+
+ it "matches a row that holds the cursor value" do
+ expect(matches).to eq(%("topics"."created_at" = :created_at))
+ end
+ end
+
+ describe "#disjuncts" do
+ subject(:disjuncts) { term.disjuncts(matched_terms) }
+
+ let(:matched_terms) { [] }
+
+ it "returns one comparison for the rows after the cursor value" do
+ expect(disjuncts).to eq([%(("topics"."created_at" > :created_at))])
+ end
+
+ context "when the keys before it match the cursor" do
+ let(:matched_terms) do
+ [described_class.for(JsonApiKit::Pagination::Keyset::Key.new(:id, model:), 12)]
+ end
+
+ it "adds an equality for each key before it" do
+ expect(disjuncts).to eq([%(("topics"."id" = :id AND "topics"."created_at" > :created_at))])
+ end
+ end
+
+ context "when the key sorts descending" do
+ let(:key) { descending_key }
+
+ it "compares the value the other way" do
+ expect(disjuncts).to eq([%(("topics"."created_at" < :created_at))])
+ end
+ end
+ end
+
+ describe "#bound_on" do
+ subject(:bounded_comparison) { term.bound_on("THE COMPARISON") }
+
+ it "bounds the comparison at the cursor value, not past it" do
+ expect(bounded_comparison).to eq(%("topics"."created_at" >= :created_at AND (THE COMPARISON)))
+ end
+
+ context "when the key sorts descending" do
+ let(:key) { descending_key }
+
+ it "bounds the comparison the other way" do
+ expect(bounded_comparison).to eq(
+ %("topics"."created_at" <= :created_at AND (THE COMPARISON)),
+ )
+ end
+ end
+ end
+
+ describe "#bindings" do
+ subject(:bindings) { term.bindings }
+
+ before { allow(key).to receive(:cast).with(value).and_return("the value of the column") }
+
+ it "binds the value the key casts" do
+ expect(bindings).to eq(created_at: "the value of the column")
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/predicate_spec.rb b/spec/lib/json_api_kit/pagination/predicate_spec.rb
new file mode 100644
index 00000000000..9ce180a6122
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/predicate_spec.rb
@@ -0,0 +1,211 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Predicate do
+ subject(:predicate) { described_class.new(keyset, values) }
+
+ let(:model) { Topic }
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:, direction: :desc),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3, 12, 0, 0, 123_456)) }
+ let(:values) { keyset.values_for(record) }
+
+ describe ".new" do
+ context "when the leading key can be null" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:pinned_at, model:, nulls: :last),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+
+ it "refuses to build the predicate" do
+ expect { predicate }.to raise_error(ArgumentError)
+ end
+ end
+ end
+
+ describe "#sql" do
+ subject(:sql) { predicate.sql }
+
+ it "compares the keys one at a time" do
+ expect(sql).to end_with(
+ '(("topics"."created_at" = :created_at AND "topics"."id" > :id) ' \
+ 'OR ("topics"."created_at" < :created_at))',
+ )
+ end
+
+ it "bounds the leading key at the cursor value" do
+ expect(sql).to start_with(%("topics"."created_at" <= :created_at AND ))
+ end
+
+ context "when the order has one key" do
+ let(:keys) { [JsonApiKit::Pagination::Keyset::Key.new(:id, model:)] }
+ let(:record) { Topic.new(id: 12) }
+
+ it "compares that key and adds no bound" do
+ expect(sql).to eq(%(("topics"."id" > :id)))
+ end
+ end
+
+ context "when every key sorts the same way" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+
+ it "compares every key at once" do
+ expect(sql).to eq(%(("topics"."created_at", "topics"."id") > (:created_at, :id)))
+ end
+ end
+
+ context "when the cursor value of a nullable key is null" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(
+ :bumped_at,
+ model:,
+ direction: :desc,
+ nulls: :last,
+ ),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3), bumped_at: nil) }
+
+ it "matches the null with IS NULL" do
+ expect(sql).to include(%("topics"."bumped_at" IS NULL))
+ end
+
+ it "leaves out a comparison that no row can satisfy" do
+ expect(sql).not_to include(%("topics"."bumped_at" <))
+ end
+ end
+
+ context "when a nullable key does not lead" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:pinned_at, model:, nulls: :last),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:record) do
+ Topic.new(id: 12, created_at: Time.utc(2026, 8, 3), pinned_at: Time.utc(2026, 7, 1))
+ end
+
+ it "reads the null rows last" do
+ expect(sql).to include(%("topics"."pinned_at" IS NULL))
+ end
+
+ it "does not compare every key at once" do
+ expect(sql).not_to include(") > (")
+ end
+ end
+
+ context "when the nulls of a null cursor value sort first" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:pinned_at, model:, nulls: :first),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3), pinned_at: nil) }
+
+ it "reads a row that holds a value after the null" do
+ expect(sql).to include(%("topics"."pinned_at" IS NOT NULL))
+ end
+ end
+
+ context "when the cursor value of a boolean key is false" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:closed, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:, direction: :desc),
+ ]
+ end
+ let(:record) { Topic.new(id: 12, closed: false) }
+
+ it "compares the false value like any other value" do
+ expect(sql).to include(%("topics"."closed" = :closed))
+ end
+ end
+
+ context "when the cursor value of the leading key is null" do
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:bumped_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:record) { Topic.new(id: 12, bumped_at: nil) }
+
+ it "moves past the null by the key behind it" do
+ expect(sql).to eq(%(("topics"."bumped_at" IS NULL AND "topics"."id" > :id)))
+ end
+ end
+ end
+
+ describe "#bindings" do
+ subject(:bindings) { predicate.bindings }
+
+ it "returns one binding for each key" do
+ expect(bindings.keys).to eq(%i[created_at id])
+ end
+ end
+
+ describe "#apply" do
+ subject(:selected_ids) { predicate.apply(scope).order(:id).map(&:id) }
+
+ fab!(:pinned_late) do
+ Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: Time.utc(2026, 8, 2))
+ end
+ fab!(:pinned_early) do
+ Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:first_unpinned) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: nil) }
+ fab!(:last_unpinned) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: nil) }
+
+ let(:keys) do
+ [
+ JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Pagination::Keyset::Key.new(:pinned_at, model:, direction: :desc, nulls: :last),
+ JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ ]
+ end
+ let(:scope) do
+ keyset.project(
+ Topic.where(id: [pinned_late.id, pinned_early.id, first_unpinned.id, last_unpinned.id]),
+ )
+ end
+ let(:record) { first_unpinned }
+
+ it "reads the next row that holds no value" do
+ expect(selected_ids).to eq([last_unpinned.id])
+ end
+
+ context "when the values are those of the last row" do
+ let(:record) { last_unpinned }
+
+ it "reads no row" do
+ expect(selected_ids).to be_empty
+ end
+ end
+
+ context "when the nullable key holds a value" do
+ let(:record) { pinned_late }
+
+ it "reads every later row, whether it holds a value or not" do
+ expect(selected_ids).to eq([pinned_early.id, first_unpinned.id, last_unpinned.id])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/row_spec.rb b/spec/lib/json_api_kit/pagination/row_spec.rb
new file mode 100644
index 00000000000..98bfa0faf26
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/row_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Row do
+ subject(:row) { described_class.new(record: topic, segment:) }
+
+ fab!(:topic)
+
+ let(:model) { Topic }
+ let(:keyset) do
+ JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)])
+ end
+ let(:segment) { JsonApiKit::Pagination::Order::Segment.new(id: 2, keyset:) }
+
+ describe "#record" do
+ it "returns the record it holds" do
+ expect(row.record).to eq(topic)
+ end
+ end
+
+ describe "#position" do
+ it "places the record in its own segment" do
+ expect(row.position.segment).to be(segment)
+ end
+ end
+
+ describe "#cursor" do
+ before { allow(row.position).to receive(:to_cursor).and_return("THE CURSOR") }
+
+ it "returns the cursor of its position" do
+ expect(row.cursor).to eq("THE CURSOR")
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/scan_spec.rb b/spec/lib/json_api_kit/pagination/scan_spec.rb
new file mode 100644
index 00000000000..2acc8b913e0
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/scan_spec.rb
@@ -0,0 +1,78 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Scan do
+ subject(:scan) { described_class.new(scope, segment:, size:, after:) }
+
+ fab!(:first_topic, :topic)
+ fab!(:second_topic, :topic)
+ fab!(:third_topic, :topic)
+
+ let(:model) { Topic }
+ let(:keyset) do
+ JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)])
+ end
+ let(:segment) { JsonApiKit::Pagination::Order::Segment.new(id: 3, keyset:) }
+ let(:scope) { Topic.where(id: [first_topic.id, second_topic.id, third_topic.id]) }
+ let(:size) { 2 }
+ let(:after) { nil }
+
+ describe "#rows" do
+ subject(:rows) { scan.rows }
+
+ it "reads the rows from the start of the segment" do
+ expect(rows.map(&:record)).to eq([first_topic, second_topic])
+ end
+
+ it "reads no more rows than the page holds" do
+ expect(rows.size).to eq(size)
+ end
+
+ it "places each row in the segment it reads" do
+ expect(rows.map { it.position.segment }).to all(be(segment))
+ end
+
+ context "when the scan starts after a row" do
+ let(:after) { [first_topic.id] }
+
+ it "reads the rows that follow it" do
+ expect(rows.map(&:record)).to eq([second_topic, third_topic])
+ end
+ end
+
+ context "when the segment holds only some of the rows" do
+ let(:segment) do
+ JsonApiKit::Pagination::Order::Segment.new(
+ id: 3,
+ keyset:,
+ condition: ->(scope) { scope.where(id: third_topic.id) },
+ )
+ end
+
+ it "reads only the rows the segment holds" do
+ expect(rows.map(&:record)).to eq([third_topic])
+ end
+ end
+ end
+
+ describe "#truncated?" do
+ it "reports that more rows follow the page" do
+ expect(scan).to be_truncated
+ end
+
+ context "when the page reads the last row of the segment" do
+ let(:size) { 3 }
+
+ it "reports that no row follows the page" do
+ expect(scan).not_to be_truncated
+ end
+ end
+
+ context "when the page holds no row" do
+ let(:size) { 0 }
+
+ it "reports that the segment holds a row" do
+ expect(scan).to be_truncated
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/window_spec.rb b/spec/lib/json_api_kit/pagination/window_spec.rb
new file mode 100644
index 00000000000..5238a1a87b4
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination/window_spec.rb
@@ -0,0 +1,132 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination::Window do
+ subject(:window) { described_class.new(scope, order:, size:, after:) }
+
+ fab!(:first_topic, :topic)
+ fab!(:second_topic, :topic)
+ fab!(:third_topic, :topic)
+
+ let(:model) { Topic }
+ let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:keys) { [key.new(:id, model:)] }
+ let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:order) { JsonApiKit::Pagination::Order.new(keyset) }
+ let(:scope) { Topic.where(id: [first_topic.id, second_topic.id, third_topic.id]) }
+ let(:third_position) { order.first.position_of(third_topic) }
+ let(:size) { 2 }
+ let(:after) { nil }
+
+ describe "#rows" do
+ subject(:records) { window.rows.map(&:record) }
+
+ it "reads the first rows of the listing" do
+ expect(records).to eq([first_topic, second_topic])
+ end
+
+ context "when the cursor sits on the last row" do
+ let(:after) { third_position }
+
+ it "reads no row" do
+ expect(records).to be_empty
+ end
+ end
+ end
+
+ describe "#truncated?" do
+ it "reports that more rows follow the page" do
+ expect(window).to be_truncated
+ end
+
+ context "when the page ends with the last row of the listing" do
+ let(:size) { 3 }
+
+ it "reports that no row follows the page" do
+ expect(window).not_to be_truncated
+ end
+ end
+ end
+
+ context "when the order reads the listing in segments" do
+ fab!(:pinned_late) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 2)) }
+ fab!(:pinned_early) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+
+ let(:keys) do
+ [key.new(:pinned_at, model:, direction: :desc, nulls: :last), key.new(:id, model:)]
+ end
+ let(:scope) do
+ Topic.where(
+ id: [pinned_late.id, pinned_early.id, first_topic.id, second_topic.id, third_topic.id],
+ )
+ end
+ let(:size) { 3 }
+
+ describe "#rows" do
+ subject(:records) { window.rows.map(&:record) }
+
+ it "reads on into the next segment to fill the page" do
+ expect(records).to eq([pinned_late, pinned_early, first_topic])
+ end
+
+ it "places each row in the segment it comes from" do
+ expect(window.rows.map { it.position.segment.id }).to eq([0, 0, 1])
+ end
+
+ context "when the page needs more rows than the segment holds" do
+ before { allow(JsonApiKit::Pagination::Scan).to receive(:new).and_call_original }
+
+ it "asks the next segment for only the rows the page still needs" do
+ window.rows
+
+ expect(JsonApiKit::Pagination::Scan).to have_received(:new).with(
+ scope,
+ a_hash_including(segment: order.segments.last, size: 1),
+ )
+ end
+
+ it "reads that segment from its start" do
+ window.rows
+
+ expect(JsonApiKit::Pagination::Scan).to have_received(:new).with(
+ scope,
+ a_hash_including(segment: order.segments.last, after: nil),
+ )
+ end
+ end
+
+ context "when the cursor sits in the leading segment" do
+ let(:after) { order.first.position_of(pinned_late) }
+
+ it "reads on from there into the next segment" do
+ expect(records).to eq([pinned_early, first_topic, second_topic])
+ end
+ end
+
+ context "when the cursor sits in the second segment" do
+ let(:after) { order.segments.last.position_of(first_topic) }
+
+ it "stays in that segment" do
+ expect(records).to eq([second_topic, third_topic])
+ end
+ end
+ end
+
+ describe "#truncated?" do
+ context "when the page ends where a segment ends" do
+ let(:size) { 2 }
+
+ it "reports that more rows follow the page" do
+ expect(window).to be_truncated
+ end
+ end
+
+ context "when the page ends with the last segment" do
+ let(:size) { 5 }
+
+ it "reports that no row follows the page" do
+ expect(window).not_to be_truncated
+ end
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination_spec.rb b/spec/lib/json_api_kit/pagination_spec.rb
new file mode 100644
index 00000000000..6e105a7f23c
--- /dev/null
+++ b/spec/lib/json_api_kit/pagination_spec.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Pagination do
+ fab!(:first_pinned) do
+ Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: Time.utc(2026, 7, 1))
+ end
+ fab!(:first_unpinned) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: nil) }
+ fab!(:second_pinned) do
+ Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: Time.utc(2026, 7, 2))
+ end
+ fab!(:second_unpinned) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: nil) }
+ fab!(:third_unpinned) { Fabricate(:topic, created_at: Time.utc(2026, 8, 2), pinned_at: nil) }
+ fab!(:third_pinned) do
+ Fabricate(:topic, created_at: Time.utc(2026, 8, 2), pinned_at: Time.utc(2026, 7, 3))
+ end
+
+ let(:model) { Topic }
+ let(:key) { described_class::Keyset::Key }
+ let(:keyset) { described_class::Keyset.new(keys) }
+ let(:order) { described_class::Order.new(keyset) }
+ let(:topics) do
+ [first_pinned, first_unpinned, second_pinned, second_unpinned, third_unpinned, third_pinned]
+ end
+ let(:scope) { Topic.where(id: topics.map(&:id)) }
+ let(:listing) { scope.order(keyset.order).pluck(:id) }
+
+ let(:paged_ids) do
+ [].tap do |ids|
+ cursor = nil
+
+ loop do
+ page = described_class::Paginator.for(scope, order:, size: 2, after: cursor)
+ ids.concat(page.rows.map { it.record.id })
+ cursor = page.next
+ break if cursor.nil?
+ end
+ end
+ end
+
+ let(:rows) do
+ described_class::Paginator.for(scope, order:, size: listing.size).rows.index_by { it.record.id }
+ end
+ let(:read_before_each_row) do
+ listing.map do
+ described_class::Paginator
+ .for(scope, order:, size: 2, before: rows[it].cursor)
+ .rows
+ .map { it.record.id }
+ end
+ end
+ let(:two_rows_before_each) { listing.each_index.map { listing[[it - 2, 0].max...it] } }
+
+ context "when a nullable key does not lead" do
+ let(:keys) do
+ [
+ key.new(:created_at, model:),
+ key.new(:pinned_at, model:, nulls: :last),
+ key.new(:id, model:),
+ ]
+ end
+
+ it "reads the whole listing, one page at a time" do
+ expect(paged_ids).to eq(listing)
+ end
+
+ it "reads the two rows before every row of the listing" do
+ expect(read_before_each_row).to eq(two_rows_before_each)
+ end
+ end
+
+ context "when the leading key is nullable" do
+ let(:keys) { [key.new(:pinned_at, model:, nulls: :last), key.new(:id, model:)] }
+
+ it "reads the whole listing, one page at a time" do
+ expect(paged_ids).to eq(listing)
+ end
+
+ it "reads the two rows before every row of the listing" do
+ expect(read_before_each_row).to eq(two_rows_before_each)
+ end
+ end
+
+ context "when the leading key sorts its nulls first" do
+ let(:keys) { [key.new(:pinned_at, model:, nulls: :first), key.new(:id, model:)] }
+
+ it "reads the whole listing, one page at a time" do
+ expect(paged_ids).to eq(listing)
+ end
+
+ it "reads the two rows before every row of the listing" do
+ expect(read_before_each_row).to eq(two_rows_before_each)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/path_spec.rb b/spec/lib/json_api_kit/path_spec.rb
new file mode 100644
index 00000000000..5d95b237daa
--- /dev/null
+++ b/spec/lib/json_api_kit/path_spec.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Path do
+ subject(:path) { described_class.for("user.groups") }
+
+ describe ".for" do
+ it "splits a path a client wrote at each dot" do
+ expect([path.current, path.next.current]).to eq(%w[user groups])
+ end
+
+ context "when one reading gives a path to the next" do
+ let(:next_path) { path.next }
+
+ it "returns the path it holds, at the relationship it reaches" do
+ expect(described_class.for(next_path)).to be(next_path)
+ end
+ end
+ end
+
+ describe "#current" do
+ it "returns the relationship to read here" do
+ expect(path.current).to eq("user")
+ end
+
+ context "when a reading is past the first relationship" do
+ it "returns the relationship to read there" do
+ expect(path.next.current).to eq("groups")
+ end
+ end
+ end
+
+ describe "#last?" do
+ it { is_expected.not_to be_last }
+
+ context "when a reading is at the end of the path" do
+ subject(:path) { described_class.for("user.groups").next }
+
+ it { is_expected.to be_last }
+ end
+ end
+
+ describe "#entered?" do
+ it { is_expected.not_to be_entered }
+
+ context "when a reading is part way along the path" do
+ subject(:path) { described_class.for("user.groups").next }
+
+ it { is_expected.to be_entered }
+ end
+ end
+
+ describe "#next" do
+ it "returns the same path, one relationship on" do
+ expect(path.next.current).to eq("groups")
+ end
+
+ context "when the path holds one relationship" do
+ subject(:path) { described_class.for("user") }
+
+ it "returns nothing" do
+ expect(path.next).to be_nil
+ end
+ end
+ end
+
+ describe "#to_s" do
+ it "returns the path as a client wrote it" do
+ expect(path.to_s).to eq("user.groups")
+ end
+
+ context "when a reading is past the first relationship" do
+ it "returns the whole path even so" do
+ expect(path.next.to_s).to eq("user.groups")
+ end
+ end
+ end
+
+ describe "#==" do
+ it "matches a path of the same relationships" do
+ expect(path).to eq(described_class.for("user.groups"))
+ end
+
+ it "differs from a path of other relationships" do
+ expect(path).not_to eq(described_class.for("user.badges"))
+ end
+
+ context "when two readings have reached different relationships of one path" do
+ it "leaves them unmatched" do
+ expect(path.next).not_to eq(described_class.for("user.groups"))
+ end
+ end
+ end
+
+ describe "#hash" do
+ it "counts two paths that match as one" do
+ expect([path, described_class.for("user.groups")].uniq.size).to eq(1)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/paths_spec.rb b/spec/lib/json_api_kit/paths_spec.rb
new file mode 100644
index 00000000000..051be2cebde
--- /dev/null
+++ b/spec/lib/json_api_kit/paths_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Paths do
+ subject(:paths) { described_class.new(%w[user groups user.groups]) }
+
+ describe "#relationship_names" do
+ subject(:relationship_names) { paths.relationship_names }
+
+ it "returns the relationships to read here" do
+ expect(relationship_names).to eq(%w[user groups])
+ end
+
+ it "returns each relationship one time" do
+ expect(relationship_names.count("user")).to eq(1)
+ end
+
+ context "when a client asks for nothing" do
+ subject(:paths) { described_class.new(nil) }
+
+ it "returns no relationship" do
+ expect(relationship_names).to be_empty
+ end
+ end
+ end
+
+ describe "#next_for" do
+ subject(:next_paths) { paths.next_for("user") }
+
+ it "returns what the resource on the other side reads" do
+ expect(next_paths.relationship_names).to eq(%w[groups])
+ end
+
+ context "when every path through that relationship ends there" do
+ subject(:next_paths) { paths.next_for("groups") }
+
+ it "returns nothing to read" do
+ expect(next_paths).to be_empty
+ end
+ end
+
+ context "when no path goes through that relationship" do
+ subject(:next_paths) { paths.next_for("category") }
+
+ it "returns nothing to read" do
+ expect(next_paths).to be_empty
+ end
+ end
+
+ context "when one reading gives its paths to the next" do
+ subject(:paths) { described_class.new(described_class.new(%w[user.groups.members])) }
+
+ it "reads them the same way" do
+ expect(paths.next_for("user").relationship_names).to eq(%w[groups])
+ end
+
+ it "keeps each path whole" do
+ expect(paths.next_for("user").map(&:to_s)).to eq(%w[user.groups.members])
+ end
+ end
+ end
+
+ describe "#+" do
+ subject(:both_paths) { paths + described_class.new(%w[category]) }
+
+ it "holds the paths of both" do
+ expect(both_paths.map(&:to_s)).to eq(%w[user groups user.groups category])
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/query/collection_spec.rb b/spec/lib/json_api_kit/query/collection_spec.rb
new file mode 100644
index 00000000000..fa26de9d4e8
--- /dev/null
+++ b/spec/lib/json_api_kit/query/collection_spec.rb
@@ -0,0 +1,205 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Query::Collection do
+ subject(:query) { described_class.new(resource, request, scoped_to:) }
+
+ fab!(:first_topic) do
+ Fabricate(:topic, title: "Segments of a listing", created_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:second_topic) do
+ Fabricate(:topic, title: "Cursors and their values", created_at: Time.utc(2026, 8, 2))
+ end
+ fab!(:third_topic) do
+ Fabricate(:topic, title: "Bands read one at a time", created_at: Time.utc(2026, 8, 3))
+ end
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ end
+ end
+ let(:request) { JsonApiKit::Request::Collection.new(params, guardian:) }
+ let(:params) { {} }
+ let(:guardian) { Guardian.new }
+ let(:scoped_to) { nil }
+
+ def request_for(params) = JsonApiKit::Request::Collection.new(params, guardian: Guardian.new)
+
+ describe ".new" do
+ let(:params) { { sort: { secrets: :asc } } }
+
+ it "reads nothing before a caller asks for records" do
+ expect { query }.not_to raise_error
+ end
+ end
+
+ describe "#rows" do
+ subject(:rows) { query.rows }
+
+ it "gives every row of the page a cursor" do
+ expect(rows.map(&:cursor)).to all(be_present)
+ end
+ end
+
+ describe "#next" do
+ subject(:next_cursor) { query.next }
+
+ let(:params) { { page: { size: 2 } } }
+
+ it "returns the cursor that starts the next page" do
+ expect(
+ described_class
+ .new(resource, request_for(page: { after: next_cursor }))
+ .records
+ .map(&:record),
+ ).to eq([third_topic])
+ end
+
+ context "when the page holds the last row of the listing" do
+ let(:params) { { page: { size: 5 } } }
+
+ it "returns nothing" do
+ expect(next_cursor).to be_nil
+ end
+ end
+ end
+
+ describe "#pages" do
+ subject(:pages) { query.pages }
+
+ let(:params) { { page: { size: 2 } } }
+
+ it "returns the cursor at each end" do
+ expect(pages).to eq(before: query.previous, after: query.next)
+ end
+ end
+
+ describe "#previous" do
+ subject(:previous_cursor) { query.previous }
+
+ let(:params) { { page: { size: 2 } } }
+
+ it "returns nothing" do
+ expect(previous_cursor).to be_nil
+ end
+
+ context "when a caller reads from further into the listing" do
+ let(:first_cursor) { described_class.new(resource, request_for({})).rows.first.cursor.to_s }
+ let(:params) { { page: { size: 2, after: first_cursor } } }
+
+ it "returns the cursor that reads the page before it" do
+ expect(previous_cursor).to be_present
+ end
+ end
+ end
+
+ describe "the fields it renders" do
+ subject(:fields) { query.records.map(&:attributes) }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ attribute :title
+ attribute :closed
+ end
+ end
+
+ it "renders every row in the order the listing reads them" do
+ expect(fields.map { it["title"] }).to eq(
+ [first_topic.title, second_topic.title, third_topic.title],
+ )
+ end
+
+ context "when the fields hold a column attribute" do
+ let(:params) { { fields: { topics: [:title] } } }
+
+ it "renders only those fields" do
+ expect(fields.first.keys).to contain_exactly("title")
+ end
+
+ it "reads only the columns those fields and the order need" do
+ expect(query.records.first.record.attributes.keys).to contain_exactly(
+ "id",
+ "title",
+ "created_at",
+ )
+ end
+ end
+
+ context "when the fields hold a block attribute" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ attribute :title
+ attribute(:slug) { |record| record.title.parameterize }
+ end
+ end
+ let(:params) { { fields: { topics: %i[title slug] } } }
+
+ it "reads the whole row" do
+ expect(query.records.first.record.attributes.keys).to include("closed", "views")
+ end
+ end
+ end
+
+ describe "#records" do
+ subject(:records) { query.records.map(&:record) }
+
+ it "reads the rows the resource exposes in the order it declares" do
+ expect(records).to eq([first_topic, second_topic, third_topic])
+ end
+
+ context "when the sort holds a key" do
+ let(:params) { { sort: { created_at: :desc } } }
+
+ it "reads the rows that way" do
+ expect(records).to eq([third_topic, second_topic, first_topic])
+ end
+ end
+
+ context "when the resource is read as part of another listing" do
+ let(:scoped_to) { Topic.where(id: [first_topic.id, third_topic.id]) }
+
+ it "reads only the rows both allow" do
+ expect(records).to eq([first_topic, third_topic])
+ end
+ end
+
+ context "when the page holds a size" do
+ let(:params) { { page: { size: 2 } } }
+
+ it "reads only that many rows" do
+ expect(records).to eq([first_topic, second_topic])
+ end
+ end
+
+ context "when the filter holds a value" do
+ let(:resource) { Class.new(super()) { filter :title } }
+ let(:params) { { filter: { title: second_topic.title } } }
+
+ it "reads only the rows that filter keeps" do
+ expect(records).to eq([second_topic])
+ end
+ end
+
+ context "when the resource declares a scope" do
+ let(:resource) do
+ Class.new(super()) { scope { |guardian| Topic.where(user_id: guardian.user&.id) } }
+ end
+ let(:guardian) { Guardian.new(second_topic.user) }
+
+ it "reads only the rows that scope exposes" do
+ expect(records).to eq([second_topic])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/query/individual_spec.rb b/spec/lib/json_api_kit/query/individual_spec.rb
new file mode 100644
index 00000000000..79d16d3235f
--- /dev/null
+++ b/spec/lib/json_api_kit/query/individual_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Query::Individual do
+ subject(:reading) { described_class.new(resource, request) }
+
+ fab!(:topic) { Fabricate(:topic, title: "The row an id names") }
+ fab!(:other_topic) { Fabricate(:topic, title: "A row nobody named") }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ end
+ end
+ let(:request) { JsonApiKit::Request::Individual.new(params, guardian:) }
+ let(:params) { { id: topic.id } }
+ let(:guardian) { Guardian.new }
+
+ describe "#record" do
+ it "returns the record with that id" do
+ expect(reading.record.record).to eq(topic)
+ end
+
+ it "renders it with the fields the resource declares" do
+ expect(reading.record.attributes).to eq("title" => topic.title)
+ end
+
+ context "when nothing is there under that id" do
+ let(:params) { { id: -1 } }
+
+ it "refuses the request instead of answering with nothing" do
+ expect { reading.record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+
+ context "when the scope withholds the row" do
+ let(:resource) { Class.new(super()) { scope { Topic.where(closed: true) } } }
+
+ it "refuses the request instead of answering with nothing" do
+ expect { reading.record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/record_spec.rb b/spec/lib/json_api_kit/record_spec.rb
new file mode 100644
index 00000000000..47045285a2a
--- /dev/null
+++ b/spec/lib/json_api_kit/record_spec.rb
@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Record do
+ subject(:record) { described_class.new(row, resource.fields, type: "topics", relationships:) }
+
+ fab!(:author, :user)
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A row read as a record") }
+
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ end
+ end
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ end
+ end
+ let(:row) { JsonApiKit::Pagination::Row.new(record: topic, segment: nil) }
+ let(:author_record) do
+ described_class.new(
+ JsonApiKit::Pagination::Row.new(record: author, segment: nil),
+ users_resource.fields,
+ type: "users",
+ )
+ end
+ let(:relationships) { {} }
+
+ describe "#attributes" do
+ it "renders the fields that the resource declares" do
+ expect(record.attributes).to eq("title" => topic.title)
+ end
+ end
+
+ describe "#id" do
+ it "returns the id as a string" do
+ expect(record.id).to eq(topic.id.to_s)
+ end
+ end
+
+ describe "#identity" do
+ it "returns the type and the id" do
+ expect(record.identity).to eq(
+ JsonApiKit::Record::Identity.new(type: "topics", id: topic.id.to_s),
+ )
+ end
+
+ it "matches another reading of the same row" do
+ expect(record.identity).to eq(
+ described_class.new(row, resource.fields(["secrets"]), type: "topics").identity,
+ )
+ end
+ end
+
+ describe "#merge" do
+ subject(:merged) { record.merge(other) }
+
+ let(:relationships) { { "user" => JsonApiKit::Linkage::ToOne.new([author_record]) } }
+ let(:other) do
+ described_class.new(row, resource.fields(["secrets"]), type: "topics", relationships: editors)
+ end
+ let(:editors) do
+ {
+ "editors" =>
+ JsonApiKit::Linkage::ToMany.new(JsonApiKit::Records.new([author_record]).page(1)),
+ }
+ end
+
+ it "holds the relationships of both readings" do
+ expect(merged.relationships.keys).to contain_exactly("user", "editors")
+ end
+
+ it "renders its own fields" do
+ expect(merged.attributes).to eq("title" => topic.title)
+ end
+
+ it "leaves this record unchanged" do
+ expect { merged }.not_to change { record.relationships }
+ end
+
+ context "when both readings hold the same relationship" do
+ let(:editors) { { "user" => JsonApiKit::Linkage::ToOne.new([]) } }
+
+ it "keeps its own relationship" do
+ expect(merged.relationships["user"].collapse { it.id }).to eq(author.id.to_s)
+ end
+ end
+ end
+
+ describe "#related_records" do
+ it "returns none where the record relates to nothing" do
+ expect(record.related_records).to be_empty
+ end
+
+ context "when the record holds one relationship" do
+ let(:relationships) { { "user" => JsonApiKit::Linkage::ToOne.new([author_record]) } }
+
+ it "returns the records under it" do
+ expect(record.related_records).to eq([author_record])
+ end
+ end
+
+ context "when the record holds several relationships" do
+ let(:relationships) do
+ {
+ "user" => JsonApiKit::Linkage::ToOne.new([author_record]),
+ "editors" =>
+ JsonApiKit::Linkage::ToMany.new(JsonApiKit::Records.new([author_record]).page(1)),
+ }
+ end
+
+ it "returns the records under all of them" do
+ expect(record.related_records).to eq([author_record, author_record])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/records_spec.rb b/spec/lib/json_api_kit/records_spec.rb
new file mode 100644
index 00000000000..371c5ed3d8d
--- /dev/null
+++ b/spec/lib/json_api_kit/records_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Records do
+ subject(:page) { described_class.new(held).page(2) }
+
+ let(:record_class) { Struct.new(:record, :cursor) }
+ let(:held) { 1.upto(3).map { record_class.new("record #{it}", "cursor #{it}") } }
+
+ describe "#page" do
+ it "holds the first records of the collection" do
+ expect(page.records.map(&:cursor)).to eq(["cursor 1", "cursor 2"])
+ end
+
+ it "returns the cursor the next page starts at" do
+ expect(page.cursor).to eq("cursor 2")
+ end
+
+ context "when the reading holds no more records than the page" do
+ let(:held) { 1.upto(2).map { record_class.new("record #{it}", "cursor #{it}") } }
+
+ it "returns no cursor" do
+ expect(page.cursor).to be_nil
+ end
+ end
+
+ context "when the reading holds fewer records than the page" do
+ let(:held) { [record_class.new("record 1", "cursor 1")] }
+
+ it "holds all of them" do
+ expect(page.records.map(&:cursor)).to eq(["cursor 1"])
+ end
+ end
+ end
+
+ describe "#fetch_all" do
+ subject(:fetched) { described_class.new(held).fetch_all(rows) }
+
+ let(:rows) { ["record 3", "record 1"] }
+
+ it "returns the records those rows name in that order" do
+ expect(fetched.map(&:record)).to eq(["record 3", "record 1"])
+ end
+
+ context "when a row matches no record" do
+ let(:rows) { ["record 1", "nowhere"] }
+
+ it "refuses to answer" do
+ expect { fetched }.to raise_error(KeyError)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/reflection_spec.rb b/spec/lib/json_api_kit/reflection_spec.rb
new file mode 100644
index 00000000000..f69f4e5b005
--- /dev/null
+++ b/spec/lib/json_api_kit/reflection_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Reflection do
+ subject(:reflection) { described_class.for(Topic.reflect_on_association(name)) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A row the kit reflects on") }
+
+ let(:name) { :user }
+
+ describe ".for" do
+ it { is_expected.to be_an_instance_of(described_class) }
+
+ context "with a through association" do
+ let(:name) { :tags }
+
+ it { is_expected.to be_an_instance_of(described_class::Through) }
+ end
+ end
+
+ describe "#owner_key" do
+ subject(:owner_key) { reflection.owner_key }
+
+ context "with a belongs_to" do
+ it { is_expected.to eq(:user_id) }
+ end
+
+ context "with a has_many" do
+ let(:name) { :posts }
+
+ it { is_expected.to eq(:id) }
+ end
+
+ context "with a through association" do
+ let(:name) { :tags }
+
+ it { is_expected.to eq(:id) }
+ end
+ end
+
+ describe "#association" do
+ subject(:association) { reflection.association([topic]) }
+
+ it { is_expected.to be_an_instance_of(JsonApiKit::Association) }
+
+ context "with a through association" do
+ let(:name) { :tags }
+
+ it { is_expected.to be_an_instance_of(JsonApiKit::Association::Through) }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/contract/collection_spec.rb b/spec/lib/json_api_kit/request/contract/collection_spec.rb
new file mode 100644
index 00000000000..71b70604214
--- /dev/null
+++ b/spec/lib/json_api_kit/request/contract/collection_spec.rb
@@ -0,0 +1,236 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
+ subject(:contract) do
+ described_class.new(
+ **params,
+ options: {
+ resource:,
+ raw_parameters: params.with_indifferent_access,
+ },
+ )
+ end
+
+ let(:params) { {} }
+ let(:cursor) { JsonApiKit::Pagination::Cursor.new([resource.order.digest, 0, 12]).to_s }
+ let(:related) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ end
+ end
+ let(:resource) do
+ users = related
+ Class.new(JsonApiKit::Resource) do
+ has_one :user, resource: users
+ model Topic
+ type :topics
+ sort :created_at
+ sort :title
+ filter :title
+ anchor :id
+ anchor :title
+ page max: 50
+ anchor(:first_unread) { |topics, _guardian| topics }
+ end
+ end
+
+ describe "Unknown parameters" do
+ context "when a parameter is unknown" do
+ let(:params) { { sorts: { created_at: :asc } } }
+
+ it "refuses the parameter" do
+ expect(contract).to be_invalid
+ expect(contract.errors).to include(:sorts)
+ end
+ end
+
+ context "when a page parameter is unknown" do
+ let(:params) { { page: { sise: 2 } } }
+
+ it "refuses it under the parameter it came in" do
+ expect(contract).to be_invalid
+ expect(contract.errors).to include(:"page.sise")
+ end
+ end
+ end
+
+ describe "Sorting" do
+ it { is_expected.to allow_value(nil, {}, { created_at: :asc }).for(:sort) }
+ it { is_expected.to allow_value({ created_at: :desc, title: :asc }).for(:sort) }
+ it { is_expected.not_to allow_value({ secrets: :asc }).for(:sort) }
+ it { is_expected.not_to allow_value({ created_at: :sideways }).for(:sort) }
+ it { is_expected.not_to allow_value("created_at", %w[created_at], 5, "").for(:sort) }
+ end
+
+ describe "Filtering" do
+ it { is_expected.to allow_value(nil, {}, { title: "a topic" }).for(:filter) }
+ it { is_expected.not_to allow_value({ secrets: "hidden" }).for(:filter) }
+ it { is_expected.not_to allow_value("title", %w[title], "").for(:filter) }
+ it { is_expected.not_to allow_value({ title: { a: 1 } }, { title: {} }).for(:filter) }
+ end
+
+ describe "Including" do
+ it { is_expected.to allow_value(nil, [], %w[user]).for(:include) }
+ it { is_expected.to allow_value("", [""]).for(:include) }
+ it { is_expected.not_to allow_value(%w[secrets], %w[user.groups]).for(:include) }
+ end
+
+ describe "Fieldsets" do
+ it { is_expected.to allow_value(nil, {}, { topics: %w[title created_at] }).for(:fields) }
+ it { is_expected.not_to allow_value("title", [1], { topics: 42 }).for(:fields) }
+ it { is_expected.not_to allow_value({ topics: "title" }).for(:fields) }
+ end
+
+ describe "Anchoring" do
+ subject(:page) { contract.page }
+
+ let(:params) { { page: {} } }
+
+ before { contract.valid? }
+
+ it { is_expected.to validate_length_of(:anchor).as_array.is_equal_to(1).allow_nil }
+ it { is_expected.to allow_value({ id: 12 }, :first_unread).for(:anchor) }
+ it { is_expected.not_to allow_value({}, { id: 12, title: "a topic" }).for(:anchor) }
+ it { is_expected.not_to allow_value({ id: { a: 1 } }, { id: %w[a b] }).for(:anchor) }
+ it { is_expected.not_to allow_value({ secrets: 12 }, :guesswork).for(:anchor) }
+
+ context "when the anchor name matches the sort" do
+ let(:params) { { sort: { title: :asc }, page: {} } }
+
+ it { is_expected.to allow_value({ title: "a topic" }).for(:anchor) }
+ end
+
+ context "when the anchor name does not match the sort" do
+ let(:params) { { sort: { created_at: :asc }, page: {} } }
+
+ it { is_expected.not_to allow_value({ title: "a topic" }).for(:anchor) }
+ it { is_expected.to allow_value({ id: 12 }, :first_unread).for(:anchor) }
+ end
+
+ context "when a cursor is present" do
+ let(:params) { { page: { after: cursor } } }
+
+ it { is_expected.to validate_absence_of(:anchor) }
+ end
+
+ context "when a window is requested" do
+ let(:params) { { page: { before_size: 2 } } }
+
+ it { is_expected.to validate_presence_of(:anchor) }
+ end
+
+ context "when the anchor is not included" do
+ let(:params) { { page: { include_anchor: false } } }
+
+ it { is_expected.to validate_presence_of(:anchor) }
+ end
+ end
+
+ describe "Pagination" do
+ subject(:page) { contract.page }
+
+ let(:params) { { page: {} } }
+ let(:cursor_not_matching_segment) do
+ JsonApiKit::Pagination::Cursor.new([resource.order.digest, 7, 12]).to_s
+ end
+ let(:cursor_not_matching_length) do
+ JsonApiKit::Pagination::Cursor.new([resource.order.digest, 0]).to_s
+ end
+
+ before { contract.valid? }
+
+ it do
+ is_expected.to validate_numericality_of(:size)
+ .only_integer
+ .is_greater_than(0)
+ .is_less_than_or_equal_to(50)
+ .allow_nil
+ end
+ it { is_expected.not_to allow_value("").for(:size) }
+ it { is_expected.to allow_value(cursor).for(:after) }
+ it { is_expected.to allow_value(cursor).for(:before) }
+ it do
+ is_expected.not_to allow_value(
+ "not-a-cursor",
+ "",
+ cursor_not_matching_length,
+ cursor_not_matching_segment,
+ ).for(:after)
+ end
+ it do
+ is_expected.not_to allow_value(
+ "not-a-cursor",
+ "",
+ cursor_not_matching_segment,
+ cursor_not_matching_length,
+ ).for(:before)
+ end
+
+ context "when there is no page" do
+ let(:params) { {} }
+
+ it { expect(contract).to be_valid }
+ end
+
+ context "when the page is not a valid object" do
+ let(:params) { { page: "big" } }
+
+ it { expect(contract).not_to be_valid }
+ end
+
+ context "when page[after] is present" do
+ let(:params) { { page: { after: cursor } } }
+
+ it { is_expected.to validate_absence_of(:before) }
+ end
+
+ context "when page[before] is present" do
+ let(:params) { { page: { before: cursor } } }
+
+ it { is_expected.to validate_absence_of(:after) }
+ end
+ end
+
+ describe "Anchor window" do
+ subject(:page) { contract.page }
+
+ let(:params) { { page: {} } }
+
+ before { contract.valid? }
+
+ it do
+ is_expected.to validate_numericality_of(:before_size)
+ .only_integer
+ .is_greater_than_or_equal_to(0)
+ .allow_nil
+ end
+ it do
+ is_expected.to validate_numericality_of(:after_size)
+ .only_integer
+ .is_greater_than_or_equal_to(0)
+ .allow_nil
+ end
+ it { is_expected.not_to allow_value("").for(:before_size) }
+ it { is_expected.not_to allow_value("").for(:after_size) }
+
+ context "when both `page[before_size]` and `page[after_size]` are provided" do
+ let(:params) { { page: { anchor: { id: 12 }, before_size: 25 } } }
+
+ it { is_expected.to allow_value(20).for(:after_size).against(:window_size) }
+ it { is_expected.not_to allow_value(25).for(:after_size).against(:window_size) }
+
+ context "when `page[include_anchor]` is false" do
+ let(:params) { { anchor: { id: 12 }, page: { before_size: 25, include_anchor: false } } }
+
+ it { is_expected.to allow_value(25).for(:after_size).against(:window_size) }
+ end
+
+ context "when both sides are 0" do
+ let(:params) { { anchor: { id: 12 }, page: { before_size: 0, include_anchor: false } } }
+
+ it { is_expected.not_to allow_value(0).for(:after_size).against(:window_size) }
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/contract/individual_spec.rb b/spec/lib/json_api_kit/request/contract/individual_spec.rb
new file mode 100644
index 00000000000..7fa1344809a
--- /dev/null
+++ b/spec/lib/json_api_kit/request/contract/individual_spec.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
+ subject(:contract) do
+ described_class.new(
+ **params,
+ options: {
+ resource:,
+ raw_parameters: params.with_indifferent_access,
+ },
+ )
+ end
+
+ let(:params) { {} }
+ let(:related) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ end
+ end
+ let(:resource) do
+ users = related
+ Class.new(JsonApiKit::Resource) do
+ has_one :user, resource: users
+ model Topic
+ type :topics
+ sort :created_at
+ filter :title
+ anchor :id
+ end
+ end
+
+ describe "Unknown parameters" do
+ context "when a parameter is unknown" do
+ let(:params) { { fieldsets: { topics: %w[title] } } }
+
+ it "refuses the parameter" do
+ expect(contract).to be_invalid
+ expect(contract.errors).to include(:fieldsets)
+ end
+ end
+
+ context "when a parameter belongs to a listing" do
+ let(:params) do
+ {
+ sort: {
+ created_at: :asc,
+ },
+ filter: {
+ title: "a topic",
+ },
+ page: {
+ anchor: {
+ id: 12,
+ },
+ size: 2,
+ },
+ }
+ end
+
+ it "refuses each of them, though the resource declares them" do
+ expect(contract).to be_invalid
+ expect(contract.errors).to include(:sort, :filter, :page)
+ end
+ end
+ end
+
+ describe "Including" do
+ it { is_expected.to allow_value(nil, [], %w[user]).for(:include) }
+ it { is_expected.to allow_value("", [""]).for(:include) }
+ it { is_expected.not_to allow_value(%w[secrets], %w[user.groups]).for(:include) }
+ end
+
+ describe "Fieldsets" do
+ it { is_expected.to allow_value(nil, {}, { topics: %w[title created_at] }).for(:fields) }
+ it { is_expected.not_to allow_value("title", [1], { topics: 42 }).for(:fields) }
+ it { is_expected.not_to allow_value({ topics: "title" }).for(:fields) }
+ end
+end
diff --git a/spec/lib/json_api_kit/request_spec.rb b/spec/lib/json_api_kit/request_spec.rb
new file mode 100644
index 00000000000..6c8a116884c
--- /dev/null
+++ b/spec/lib/json_api_kit/request_spec.rb
@@ -0,0 +1,226 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request do
+ subject(:request) { described_class::Collection.new(params, guardian:) }
+
+ let(:params) { {} }
+ let(:guardian) { Guardian.new }
+
+ describe "#scope" do
+ subject(:scope) { request.scope(from: Topic.all) }
+
+ fab!(:topic) { Fabricate(:topic, title: "The row an id names") }
+
+ it "returns every row on offer" do
+ expect(scope).to eq(Topic.all.to_a)
+ end
+
+ context "when a caller asks for one record" do
+ subject(:request) { described_class::Individual.new(params, guardian:) }
+
+ let(:params) { { id: topic.id } }
+
+ it "returns only the row with that id" do
+ expect(scope).to eq([topic])
+ end
+ end
+ end
+
+ describe "#for_sideload" do
+ subject(:for_sideload) { request.for_sideload(JsonApiKit::Paths.new(%w[groups])) }
+
+ let(:params) do
+ {
+ fields: {
+ users: %i[username],
+ },
+ include: %w[user.groups],
+ sort: {
+ created_at: :desc,
+ },
+ filter: {
+ title: "a title",
+ },
+ page: {
+ size: 2,
+ },
+ }
+ end
+
+ it "asks for the paths of the sideload" do
+ expect(for_sideload[:include].map(&:to_s)).to eq(%w[groups])
+ end
+
+ it "asks for the fields of every type" do
+ expect(for_sideload[:fields]).to eq("users" => %w[username])
+ end
+
+ it "asks nothing else of the related resource" do
+ expect(for_sideload.keys).to contain_exactly(:fields, :include)
+ end
+
+ context "when a caller asks for one record" do
+ subject(:request) { described_class::Individual.new(params, guardian:) }
+
+ let(:params) { { id: 12, fields: { users: %i[username] } } }
+
+ it "leaves the id out" do
+ expect(for_sideload.keys).to contain_exactly(:fields, :include)
+ end
+ end
+ end
+
+ describe "#including" do
+ subject(:including) { request.including }
+
+ let(:params) { { include: %w[user user.groups] } }
+
+ it "returns each path" do
+ expect(including.map(&:to_s)).to eq(%w[user user.groups])
+ end
+
+ context "when a caller spells the paths as symbols" do
+ let(:params) { { include: %i[user] } }
+
+ it "returns the same paths" do
+ expect(including.map(&:to_s)).to eq(%w[user])
+ end
+ end
+
+ context "when there is no include parameter" do
+ let(:params) { {} }
+
+ it "returns no path" do
+ expect(including).to be_empty
+ end
+ end
+ end
+
+ describe "#ordering" do
+ subject(:ordering) { request.ordering }
+
+ let(:params) { { sort: { created_at: :desc } } }
+
+ it "returns each sort by name with its direction" do
+ expect(ordering).to eq("created_at" => :desc)
+ end
+
+ context "when there is no sort parameter" do
+ let(:params) { {} }
+
+ it "returns no sort" do
+ expect(ordering).to be_empty
+ end
+ end
+
+ context "when a caller spells the parameters as strings" do
+ let(:params) { { "sort" => { "created_at" => "desc" } } }
+
+ it "returns the same ordering" do
+ expect(ordering).to eq("created_at" => :desc)
+ end
+ end
+ end
+
+ describe "#filtering" do
+ subject(:filtering) { request.filtering }
+
+ let(:params) { { filter: { title: "a title" } } }
+
+ it "returns each filter by name with its value" do
+ expect(filtering).to eq("title" => "a title")
+ end
+
+ context "when there is no filter parameter" do
+ let(:params) { {} }
+
+ it "returns no filter" do
+ expect(filtering).to be_empty
+ end
+ end
+ end
+
+ describe "#fields" do
+ subject(:fields) { request.fields }
+
+ let(:params) { { fields: { topics: [:title] } } }
+
+ it "returns the fields of each type" do
+ expect(fields).to eq("topics" => %w[title])
+ end
+
+ context "when there is no fields parameter" do
+ let(:params) { {} }
+
+ it "returns no field" do
+ expect(fields).to be_empty
+ end
+ end
+ end
+
+ describe "#page" do
+ subject(:page) { request.page }
+
+ it "returns the page at the start of the listing" do
+ expect(page).to be_a(JsonApiKit::Page::Requested::First)
+ end
+
+ context "when the page holds an after cursor" do
+ let(:params) { { page: { after: JsonApiKit::Pagination::Cursor.new([12]).to_s } } }
+
+ it "returns the page that carries on from it" do
+ expect(page).to be_a(JsonApiKit::Page::Requested::After)
+ end
+ end
+
+ context "when the page holds a before cursor" do
+ let(:params) { { page: { before: JsonApiKit::Pagination::Cursor.new([12]).to_s } } }
+
+ it "returns the page before it" do
+ expect(page).to be_a(JsonApiKit::Page::Requested::Before)
+ end
+ end
+
+ context "when the cursor cannot be read" do
+ let(:params) { { page: { after: "not a cursor" } } }
+
+ it "refuses the request" do
+ expect { page }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "when there is an anchor parameter" do
+ let(:params) { { page: { anchor: { id: 12 } } } }
+
+ it "returns the page around it" do
+ expect(page).to be_a(JsonApiKit::Page::Requested::Around)
+ end
+ end
+ end
+
+ describe "#anchoring" do
+ subject(:anchoring) { request.anchoring }
+
+ let(:params) { { page: { anchor: { id: 12 } } } }
+
+ it "returns that anchor" do
+ expect(anchoring.name).to eq("id")
+ end
+
+ context "when there is no anchor parameter" do
+ let(:params) { {} }
+
+ it "returns nothing" do
+ expect(anchoring).to be_nil
+ end
+ end
+ end
+
+ describe "#guardian" do
+ subject(:request_guardian) { request.guardian }
+
+ it "returns whoever asks" do
+ expect(request_guardian).to be(guardian)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/resource_spec.rb b/spec/lib/json_api_kit/resource_spec.rb
new file mode 100644
index 00000000000..1a6d0eae949
--- /dev/null
+++ b/spec/lib/json_api_kit/resource_spec.rb
@@ -0,0 +1,510 @@
+# frozen_string_literal: true
+
+module SpecBlog
+ Post = Class.new
+
+ class PostResource < JsonApiKit::Resource
+ end
+
+ class CommentThreadResource < JsonApiKit::Resource
+ end
+
+ class UnbackedResource < JsonApiKit::Resource
+ end
+end
+
+RSpec.describe JsonApiKit::Resource do
+ subject(:resource) { SpecBlog::PostResource }
+
+ let(:guardian) { Guardian.new }
+ let(:group_resource) do
+ Class.new(described_class) do
+ model Group
+ type :groups
+ end
+ end
+ let(:user_resource) do
+ related = group_resource
+
+ Class.new(described_class) do
+ model User
+ type :users
+ has_many :groups, resource: related
+ end
+ end
+ let(:topic_resource) do
+ related = user_resource
+
+ Class.new(described_class) do
+ model Topic
+ type :topics
+ sort :created_at
+ sort :ran_at, column: :last_posted_at
+ default_sort ran_at: :desc
+ unique_by :title, :id
+ filter :title
+ page default: 2, max: 10
+ attribute :title
+ has_one :user, resource: related
+ has_many :posts, resource: related
+ includes "user.groups"
+ end
+ end
+
+ describe ".model" do
+ subject(:model) { resource.model }
+
+ it "infers the model in the resource's own namespace" do
+ expect(model).to eq(SpecBlog::Post)
+ end
+
+ context "when no model matches the resource name" do
+ subject(:resource) { SpecBlog::UnbackedResource }
+
+ it "asks for a declaration" do
+ expect { model }.to raise_error(described_class::MissingDeclaration, /Unbacked/)
+ end
+ end
+
+ context "when the resource has no name to infer from" do
+ subject(:resource) { Class.new(described_class) }
+
+ it "asks for a declaration" do
+ expect { model }.to raise_error(described_class::MissingDeclaration)
+ end
+ end
+
+ context "when the resource declares a model" do
+ subject(:resource) { Class.new(described_class) { model Category } }
+
+ it "returns the model it declares" do
+ expect(model).to eq(Category)
+ end
+ end
+
+ context "when the resource declares another model after a reading" do
+ subject(:resource) { Class.new(described_class) { model Category } }
+
+ before do
+ resource.model
+ resource.model(Topic)
+ end
+
+ it "returns the new model" do
+ expect(model).to eq(Topic)
+ end
+ end
+
+ context "when the resource declares the model by name" do
+ subject(:resource) { Class.new(described_class) { model :category } }
+
+ it "returns the model that name matches" do
+ expect(model).to eq(Category)
+ end
+ end
+
+ context "when that name is a path" do
+ subject(:resource) { Class.new(described_class) { model "spec_blog/post" } }
+
+ it "returns the model in that namespace" do
+ expect(model).to eq(SpecBlog::Post)
+ end
+ end
+
+ context "when that name matches no model" do
+ subject(:resource) { Class.new(described_class) { model :nowhere_to_be_found } }
+
+ it "refuses the model name" do
+ expect { model }.to raise_error(described_class::MissingDeclaration, /NowhereToBeFound/)
+ end
+ end
+
+ context "when a resource inherits from another" do
+ subject(:resource) { Class.new(parent) }
+
+ let(:parent) { Class.new(described_class) { model Category } }
+
+ it "returns the model declared above it" do
+ expect(model).to eq(Category)
+ end
+
+ context "when it declares a model of its own" do
+ before { resource.model(Topic) }
+
+ it "leaves the model above it alone" do
+ expect(parent.model).to eq(Category)
+ end
+ end
+ end
+ end
+
+ describe ".type" do
+ subject(:type) { resource.type }
+
+ it "infers a plural type from the resource name without the namespace" do
+ expect(type).to eq("posts")
+ end
+
+ context "when the resource name holds several words" do
+ subject(:resource) { SpecBlog::CommentThreadResource }
+
+ it "spells the type with underscores" do
+ expect(type).to eq("comment_threads")
+ end
+ end
+
+ context "when the resource declares a type" do
+ subject(:resource) { Class.new(described_class) { type :threads } }
+
+ it "returns that type as a string" do
+ expect(type).to eq("threads")
+ end
+ end
+
+ context "when the resource has no name to infer from" do
+ subject(:resource) { Class.new(described_class) }
+
+ it "asks for a declaration" do
+ expect { type }.to raise_error(described_class::MissingDeclaration)
+ end
+ end
+
+ context "when a resource inherits from another" do
+ subject(:resource) { Class.new(parent) }
+
+ let(:parent) { Class.new(described_class) { type :threads } }
+
+ it "returns the type declared above it" do
+ expect(type).to eq("threads")
+ end
+
+ context "when it declares a type of its own" do
+ before { resource.type(:posts) }
+
+ it "leaves the type above it alone" do
+ expect(parent.type).to eq("threads")
+ end
+ end
+ end
+ end
+
+ describe ".schema" do
+ it "returns a schema for the model it exposes" do
+ expect(topic_resource.schema.model).to eq(Topic)
+ end
+ end
+
+ describe ".sort" do
+ it "lets a request order the listing by the name it declares" do
+ expect(topic_resource.order("created_at" => :desc).leading.name).to eq(:created_at)
+ end
+ end
+
+ describe ".sort_names" do
+ it "returns the name of every sort the resource declares" do
+ expect(topic_resource.sort_names).to eq(%w[created_at ran_at])
+ end
+
+ context "when the resource declares one more after a reading" do
+ before do
+ topic_resource.sort_names
+ topic_resource.sort(:closed)
+ end
+
+ it "returns the new name too" do
+ expect(topic_resource.sort_names).to include("closed")
+ end
+ end
+
+ context "when a resource inherits from another" do
+ subject(:child) { Class.new(topic_resource) }
+
+ before { child.sort(:title) }
+
+ it "inherits the sorts of its parent" do
+ expect(child.sort_names).to include("created_at")
+ end
+
+ it "leaves the resource it inherits from alone" do
+ expect(topic_resource.sort_names).not_to include("title")
+ end
+ end
+ end
+
+ describe ".default_sort" do
+ it "reads a listing in the order the resource declares" do
+ expect(topic_resource.order.leading.name).to eq(:last_posted_at)
+ end
+
+ context "when the resource declares no such sort" do
+ it "refuses the declaration" do
+ expect {
+ Class.new(described_class) do
+ model Topic
+ default_sort creatd_at: :asc
+ end
+ }.to raise_error(JsonApiKit::Resource::Sorting::UndeclaredDefault, /creatd_at/)
+ end
+ end
+ end
+
+ describe ".unique_by" do
+ it "breaks ties by those columns in that sequence" do
+ expect(topic_resource.order("created_at" => :desc).columns).to eq(%i[created_at title id])
+ end
+ end
+
+ describe ".filter" do
+ subject(:kept_ids) do
+ topic_resource.apply_filters(Topic.all, "title" => kept_topic.title).map(&:id)
+ end
+
+ fab!(:kept_topic) { Fabricate(:topic, title: "The rows a filter keeps") }
+ fab!(:dropped_topic) { Fabricate(:topic, title: "The rows it leaves behind") }
+
+ it "lets a request narrow the listing by the name it declares" do
+ expect(kept_ids).to contain_exactly(kept_topic.id)
+ end
+
+ context "when the resource declares one more after a reading" do
+ subject(:kept_ids) { topic_resource.apply_filters(Topic.all, "closed" => false).map(&:id) }
+
+ before do
+ topic_resource.apply_filters(Topic.all)
+ topic_resource.filter(:closed)
+ end
+
+ it "narrows by the new filter too" do
+ expect(kept_ids).to include(kept_topic.id)
+ end
+ end
+ end
+
+ describe ".attribute" do
+ subject(:attribute_values) { topic_resource.fields.attributes.values_for(topic) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A field a resource renders") }
+
+ it "renders the field the resource declares" do
+ expect(attribute_values).to eq("title" => topic.title)
+ end
+
+ context "when the resource declares one more after a reading" do
+ before do
+ topic_resource.fields.attributes
+ topic_resource.attribute(:closed)
+ end
+
+ it "renders the new field too" do
+ expect(attribute_values).to include("closed")
+ end
+ end
+ end
+
+ describe ".has_one" do
+ subject(:user_relationships) { topic_resource.fields.relationships.pick(%w[user]) }
+
+ it "relates the resource to one record of another" do
+ expect(user_relationships.first.resource).to eq(user_resource)
+ end
+
+ it "lets a request include the relationship" do
+ expect(topic_resource.allow(JsonApiKit::Paths.new(%w[user])).map(&:to_s)).to eq(%w[user])
+ end
+
+ context "when the resource declares one more after a reading" do
+ subject(:category_relationships) { topic_resource.fields.relationships.pick(%w[category]) }
+
+ before do
+ topic_resource.fields
+ topic_resource.has_one(:category, resource: user_resource)
+ end
+
+ it "relates to the new resource too" do
+ expect(category_relationships.map(&:name)).to eq(%w[category])
+ end
+ end
+ end
+
+ describe ".has_many" do
+ subject(:posts_relationships) { topic_resource.fields.relationships.pick(%w[posts]) }
+
+ it "relates the resource to many records of another" do
+ expect(posts_relationships.first).to be_a(JsonApiKit::Declarations::Relationship::ToMany)
+ end
+ end
+
+ describe ".resolves?" do
+ let(:relationships) { instance_spy(JsonApiKit::Declarations::Relationships) }
+ let(:path) { JsonApiKit::Path.for("user") }
+
+ before do
+ allow(JsonApiKit::Declarations::Relationships).to receive(:new).and_return(relationships)
+ end
+
+ it "asks its relationships to resolve the path" do
+ topic_resource.resolves?(path)
+
+ expect(relationships).to have_received(:resolves?).with(path)
+ end
+ end
+
+ describe ".includes" do
+ subject(:allowed_paths) { topic_resource.allow(JsonApiKit::Paths.new(%w[user.groups])) }
+
+ it "lets a request read a path through a relationship" do
+ expect(allowed_paths.map(&:to_s)).to eq(%w[user.groups])
+ end
+
+ context "when the path reads a relationship no resource declares" do
+ before { topic_resource.includes("user.badges") }
+
+ it "refuses to read the resource" do
+ expect { allowed_paths }.to raise_error(
+ JsonApiKit::Declarations::IncludePaths::Unresolved,
+ /user\.badges/,
+ )
+ end
+ end
+
+ context "when a resource inherits from another" do
+ subject(:child) { Class.new(topic_resource) }
+
+ before { child.includes("posts.groups") }
+
+ it "reads the paths declared above it" do
+ expect(child.allow(JsonApiKit::Paths.new(%w[user.groups])).map(&:to_s)).to eq(
+ %w[user.groups],
+ )
+ end
+
+ it "leaves the resource it inherits from alone" do
+ expect { topic_resource.allow(JsonApiKit::Paths.new(%w[posts.groups])) }.to raise_error(
+ KeyError,
+ )
+ end
+ end
+ end
+
+ describe ".page" do
+ it "returns the size the resource declares" do
+ expect(topic_resource.page_limits.size(nil)).to eq(2)
+ end
+
+ context "when the resource declares each bound in its own call" do
+ subject(:limits) do
+ Class
+ .new(described_class) do
+ model Topic
+ page default: 20
+ page max: 50
+ end
+ .page_limits
+ end
+
+ it "keeps the size the earlier call declares" do
+ expect(limits.size(nil)).to eq(20)
+ end
+
+ it "keeps the maximum the later call declares" do
+ expect(limits.max).to eq(50)
+ end
+ end
+
+ context "when the default is larger than the maximum" do
+ it "refuses the declaration" do
+ expect {
+ Class.new(described_class) do
+ model Topic
+ page default: 200
+ page max: 50
+ end
+ }.to raise_error(JsonApiKit::Page::Limits::OutOfRange)
+ end
+ end
+ end
+
+ describe ".page_size" do
+ it "returns the size a page reads at" do
+ expect(topic_resource.page_size).to eq(2)
+ end
+ end
+
+ describe ".anchored_by?" do
+ subject(:resource) { Class.new(topic_resource) { anchor :created_at } }
+
+ let(:ordering) { { "created_at" => :asc } }
+
+ it { is_expected.to be_anchored_by(anchor_name: :created_at, ordering:) }
+
+ context "when the order does not read by that anchor" do
+ let(:ordering) { { "ran_at" => :desc } }
+
+ it { is_expected.not_to be_anchored_by(anchor_name: :created_at, ordering:) }
+ end
+
+ context "when the resource declares no anchor by that name" do
+ it { is_expected.to be_anchored_by(anchor_name: :first_unread) }
+ end
+ end
+
+ describe ".scope_for" do
+ subject(:exposed_scope) { topic_resource.scope_for(guardian) }
+
+ it "returns every row of the model" do
+ expect(exposed_scope.to_sql).to eq(Topic.all.to_sql)
+ end
+
+ context "when the resource declares a scope" do
+ subject(:exposed_scope) { closed_topics.scope_for(guardian) }
+
+ let(:closed_topics) do
+ Class.new(described_class) do
+ model Topic
+ scope { |guardian| Topic.where(closed: true) }
+ end
+ end
+
+ it "returns the rows that scope allows" do
+ expect(exposed_scope.to_sql).to eq(Topic.where(closed: true).to_sql)
+ end
+ end
+ end
+
+ describe ".all" do
+ before { allow(JsonApiKit::Query::Collection).to receive(:new) }
+
+ it "reads a listing for the request a caller sends" do
+ topic_resource.all({ sort: { created_at: :asc } }, guardian:)
+
+ expect(JsonApiKit::Query::Collection).to have_received(:new).with(
+ topic_resource,
+ an_object_having_attributes(ordering: { "created_at" => :asc }, guardian:),
+ scoped_to: nil,
+ )
+ end
+ end
+
+ describe ".paged_from?" do
+ fab!(:topic) { Fabricate(:topic, title: "A page read from a cursor") }
+
+ let(:ordering) { { "created_at" => :asc } }
+ let(:cursor) { topic_resource.order(ordering).first.position_of(topic).to_cursor }
+
+ it "accepts a cursor from the order it declares" do
+ expect(topic_resource).to be_paged_from(cursor, ordering:)
+ end
+ end
+
+ describe ".order" do
+ it "splits the order in two where a column allows null" do
+ expect(topic_resource.order("ran_at" => :desc).segments.size).to eq(2)
+ end
+
+ context "when no column of the order allows null" do
+ it "reads the listing in one segment" do
+ expect(topic_resource.order("created_at" => :desc).segments.size).to eq(1)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/schema_spec.rb b/spec/lib/json_api_kit/schema_spec.rb
new file mode 100644
index 00000000000..e16304d4809
--- /dev/null
+++ b/spec/lib/json_api_kit/schema_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Schema do
+ subject(:schema) { described_class.new(Topic) }
+
+ fab!(:topic) { Fabricate(:topic, title: "A row the kit asks about") }
+
+ describe "#primary_key" do
+ it "returns the column that identifies a row" do
+ expect(schema.primary_key).to eq(:id)
+ end
+ end
+
+ describe "#column" do
+ it "returns the column the model holds under that name" do
+ expect(schema.column("title")).to eq(:title)
+ end
+
+ context "when a caller spells the name as a symbol" do
+ it "returns the same column" do
+ expect(schema.column(:title)).to eq(:title)
+ end
+ end
+
+ context "when the model holds no column under that name" do
+ it "returns nothing" do
+ expect(schema.column("worked_out_somehow")).to be_nil
+ end
+ end
+ end
+
+ describe "#nullable?" do
+ context "when the column forbids null" do
+ it { is_expected.not_to be_nullable("title") }
+ end
+
+ context "when the column allows null" do
+ it { is_expected.to be_nullable("category_id") }
+ end
+
+ context "when the model holds no column under that name" do
+ it "returns true, having nothing to promise otherwise" do
+ expect(schema).to be_nullable("worked_out_somehow")
+ end
+ end
+ end
+
+ describe "#association" do
+ it "returns an association between the two tables" do
+ expect(schema.association(:user, [topic])).to be_an_instance_of(JsonApiKit::Association)
+ end
+
+ context "when the relationship goes through another table" do
+ it "returns an association that reads the table between them" do
+ expect(schema.association(:tags, [topic])).to be_a(JsonApiKit::Association::Through)
+ end
+ end
+ end
+ describe "#table_of" do
+ subject(:table) { schema.table_of(:user) }
+
+ it { is_expected.to eq("users") }
+
+ context "when the association doesn’t exist" do
+ subject(:table) { schema.table_of(:author) }
+
+ it { expect { table }.to raise_error(described_class::MissingAssociation, /author/) }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/scoping_spec.rb b/spec/lib/json_api_kit/scoping_spec.rb
new file mode 100644
index 00000000000..27fe9f5dee1
--- /dev/null
+++ b/spec/lib/json_api_kit/scoping_spec.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Scoping do
+ subject(:scoping) { described_class.for(scoped_to) }
+
+ fab!(:topic)
+ fab!(:another, :topic)
+
+ let(:scoped_to) { Topic.where(id: topic.id) }
+ let(:requested) { JsonApiKit::Page::Requested.for }
+
+ describe "#apply" do
+ it "keeps a listing to those rows" do
+ expect(scoping.apply(Topic.all).map(&:id)).to eq([topic.id])
+ end
+
+ context "when a caller keeps it to nothing" do
+ let(:scoped_to) { nil }
+
+ it "leaves the listing whole" do
+ expect(scoping.apply(Topic.all).map(&:id)).to contain_exactly(topic.id, another.id)
+ end
+ end
+ end
+
+ describe "#page" do
+ it "returns that page" do
+ expect(scoping.page(requested)).to be(requested)
+ end
+
+ context "when a sideload keeps it to the rows a relationship reaches" do
+ let(:scoped_to) { JsonApiKit::Schema.new(Topic).association(:posts, [topic]) }
+
+ it "reads one page for each owner instead" do
+ expect(scoping.page(requested)).to be_a(JsonApiKit::Page::PerOwner)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/sideload_spec.rb b/spec/lib/json_api_kit/sideload_spec.rb
new file mode 100644
index 00000000000..d0d38c18b03
--- /dev/null
+++ b/spec/lib/json_api_kit/sideload_spec.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Sideload do
+ subject(:sideload) { described_class.new(relationship, paths:, rows:, request:, schema:) }
+
+ fab!(:author, :user)
+ fab!(:topic) { Fabricate(:topic, user: author, title: "A topic read with its author") }
+
+ let(:users_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ end
+ end
+ let(:relationship) do
+ JsonApiKit::Declarations::Relationship::ToOne.new(:user, resource: users_resource)
+ end
+ let(:paths) { JsonApiKit::Paths.new([]) }
+ let(:records) { [topic] }
+ let(:rows) { records.map { JsonApiKit::Pagination::Row.new(record: it, segment: nil) } }
+ let(:params) { {} }
+ let(:request) { JsonApiKit::Request::Collection.new(params, guardian: Guardian.new) }
+ let(:schema) { JsonApiKit::Schema.new(Topic) }
+
+ describe "#linkage_for" do
+ subject(:linkage) { sideload.linkage_for(rows.first) }
+
+ it "holds the record that the row relates to" do
+ expect(linkage.records.map(&:record)).to eq([author])
+ end
+
+ it "holds it under the linkage that the relationship declares" do
+ expect(linkage).to be_a(JsonApiKit::Linkage::ToOne)
+ end
+
+ context "when the row relates to nothing" do
+ fab!(:without_category) { Fabricate(:private_message_topic, title: "A topic in no category") }
+
+ let(:categories_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Category
+ type :categories
+ end
+ end
+ let(:relationship) do
+ JsonApiKit::Declarations::Relationship::ToOne.new(:category, resource: categories_resource)
+ end
+ let(:records) { [without_category] }
+
+ it "holds no record" do
+ expect(linkage.records).to be_empty
+ end
+ end
+
+ context "when a path reads past the relationship" do
+ let(:paths) { JsonApiKit::Paths.new(%w[user.groups]).next_for("user") }
+
+ before { allow(relationship).to receive(:listing).and_call_original }
+
+ it "gives the rest of the path to the related resource" do
+ linkage
+ expect(relationship).to have_received(:listing).with(
+ a_hash_including(include: paths),
+ any_args,
+ )
+ end
+ end
+
+ context "when a request asks for fields of the related type" do
+ let(:params) { { fields: { users: [:username] } } }
+
+ it "renders the related record as those fields" do
+ expect(linkage.records.map(&:attributes)).to eq([{ "username" => author.username }])
+ end
+ end
+
+ context "when the page holds several rows" do
+ fab!(:another) { Fabricate(:topic, user: author, title: "Another topic by that author") }
+
+ let(:records) { [topic, another] }
+ let(:reads_of_users) do
+ track_sql_queries { rows.each { sideload.linkage_for(it) } }.grep(/FROM "users"/).size
+ end
+
+ def related_record(row) = sideload.linkage_for(row).records.first
+
+ it "reads the related rows of them all in one query" do
+ expect(reads_of_users).to eq(1)
+ end
+
+ it "gives two rows that relate to one row the same record" do
+ expect(related_record(rows.first)).to be(related_record(rows.last))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/sideloads_spec.rb b/spec/lib/json_api_kit/sideloads_spec.rb
new file mode 100644
index 00000000000..69bf389d25d
--- /dev/null
+++ b/spec/lib/json_api_kit/sideloads_spec.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Sideloads do
+ subject(:sideloads) { described_class.for(relationships, paths:, rows:, request:, schema:) }
+
+ fab!(:author, :user)
+ fab!(:category) { Fabricate(:category, name: "Where the topic sits") }
+ fab!(:topic) do
+ Fabricate(:topic, user: author, category:, title: "A topic read with two relations")
+ end
+
+ let(:groups_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Group
+ type :groups
+ end
+ end
+ let(:users_resource) do
+ related = groups_resource
+
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ has_many :groups, resource: related
+ end
+ end
+ let(:categories_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Category
+ type :categories
+ end
+ end
+ let(:to_one) { JsonApiKit::Declarations::Relationship::ToOne }
+ let(:relationships) do
+ [
+ to_one.new(:user, resource: users_resource),
+ to_one.new(:category, resource: categories_resource),
+ ]
+ end
+ let(:paths) { JsonApiKit::Paths.new(nil) }
+ let(:rows) { [JsonApiKit::Pagination::Row.new(record: topic, segment: nil)] }
+ let(:request) { JsonApiKit::Request::Collection.new({}, guardian: Guardian.new) }
+ let(:schema) { JsonApiKit::Schema.new(Topic) }
+
+ describe "#linkage_for" do
+ subject(:linkage) { sideloads.linkage_for(rows.first) }
+
+ let(:related_rows) { linkage.transform_values { it.records.map(&:record) } }
+
+ it "holds one linkage under the name of each relationship" do
+ expect(linkage.keys).to eq(%w[user category])
+ end
+
+ it "holds what the row relates to under each of them" do
+ expect(related_rows).to eq("user" => [author], "category" => [category])
+ end
+
+ context "when a reading renders no relationship" do
+ let(:relationships) { [] }
+
+ it "holds nothing" do
+ expect(linkage).to be_empty
+ end
+ end
+
+ context "when a path reads past a relationship" do
+ let(:paths) { JsonApiKit::Paths.new(%w[user.groups]) }
+ let(:forwarded) { [] }
+
+ before do
+ allow(JsonApiKit::Sideload).to receive(:new) { |_, paths:, **| forwarded << paths.to_a }
+ end
+
+ it "gives each relationship the paths that continue through it" do
+ sideloads
+ expect(forwarded.map { it.map(&:to_s) }).to eq([%w[user.groups], []])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/url_spec.rb b/spec/lib/json_api_kit/url_spec.rb
new file mode 100644
index 00000000000..a37b587aa6d
--- /dev/null
+++ b/spec/lib/json_api_kit/url_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Url do
+ subject(:url) { described_class.new(address, parameters) }
+
+ let(:address) { "https://example.com/api/topics" }
+ let(:parameters) { { "page" => { "size" => "2" }, "sort" => "created_at" } }
+
+ describe "#to_s" do
+ it "returns the address with the parameters it carries" do
+ expect(url.to_s).to eq("https://example.com/api/topics?page%5Bsize%5D=2&sort=created_at")
+ end
+
+ context "when it carries no parameter" do
+ let(:parameters) { {} }
+
+ it "returns the address on its own" do
+ expect(url.to_s).to eq("https://example.com/api/topics")
+ end
+ end
+ end
+
+ describe "#at" do
+ it "adds the cursor to the parameters it carries" do
+ expect(url.at(after: "a-cursor").to_s).to eq(
+ "https://example.com/api/topics?page%5Bafter%5D=a-cursor&page%5Bsize%5D=2&sort=created_at",
+ )
+ end
+
+ it "leaves this URL unchanged" do
+ expect { url.at(after: "a-cursor") }.not_to change { url.to_s }
+ end
+
+ context "when it already reads after a cursor" do
+ let(:parameters) { { "page" => { "size" => "2", "after" => "read-from-here" } } }
+
+ it "drops the other end" do
+ expect(url.at(before: "a-cursor").to_s).to eq(
+ "https://example.com/api/topics?page%5Bbefore%5D=a-cursor&page%5Bsize%5D=2",
+ )
+ end
+ end
+
+ context "when it carries a window around an anchor" do
+ let(:parameters) do
+ {
+ "page" => {
+ "anchor" => {
+ "id" => "12",
+ },
+ "before_size" => "1",
+ "after_size" => "1",
+ "include_anchor" => "false",
+ "size" => "2",
+ },
+ }
+ end
+
+ it "drops the anchor and the window, and keeps the page size" do
+ expect(url.at(after: "a-cursor").to_s).to eq(
+ "https://example.com/api/topics?page%5Bafter%5D=a-cursor&page%5Bsize%5D=2",
+ )
+ end
+ end
+
+ context "when it carries no parameter" do
+ let(:parameters) { {} }
+
+ it "carries only that cursor" do
+ expect(url.at(after: "a-cursor").to_s).to eq(
+ "https://example.com/api/topics?page%5Bafter%5D=a-cursor",
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/urls_spec.rb b/spec/lib/json_api_kit/urls_spec.rb
new file mode 100644
index 00000000000..bfc1cc048a5
--- /dev/null
+++ b/spec/lib/json_api_kit/urls_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Urls do
+ subject(:urls) { described_class.new(base:, current:, parameters:) }
+
+ let(:base) { "https://example.com/api" }
+ let(:current) { "https://example.com/api/topics" }
+ let(:parameters) { { "page" => { "size" => "2" }, "sort" => "created_at" } }
+
+ describe "#current" do
+ it "returns the URL a caller read with the parameters they sent" do
+ expect(urls.current.to_s).to eq(
+ "https://example.com/api/topics?page%5Bsize%5D=2&sort=created_at",
+ )
+ end
+ end
+
+ describe "#record" do
+ it "returns the URL of one record" do
+ expect(urls.record("topics", "5").to_s).to eq("https://example.com/api/topics/5")
+ end
+
+ it "carries only the cursor a caller adds" do
+ expect(urls.record("topics", "5").at(after: "a-cursor").to_s).to eq(
+ "https://example.com/api/topics/5?page%5Bafter%5D=a-cursor",
+ )
+ end
+ end
+
+ describe "#relationship" do
+ it "returns the URL of the relationship itself" do
+ expect(urls.relationship("topics", "5", "posts").to_s).to eq(
+ "https://example.com/api/topics/5/relationships/posts",
+ )
+ end
+ end
+
+ describe "#related" do
+ it "returns the URL of the records a relationship points at" do
+ expect(urls.related("topics", "5", "posts").to_s).to eq(
+ "https://example.com/api/topics/5/posts",
+ )
+ end
+ end
+end