Skip to content

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

DEV: Extract the JSON:API ActiveRecord adapter (#45004)

Loïc Guitaut965cd03f1ef0
diff --git a/lib/json_api_kit/adapter.rb b/lib/json_api_kit/adapter.rb
new file mode 100644
index 00000000000..c30fa62e93b
--- /dev/null
+++ b/lib/json_api_kit/adapter.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Adapter
+ class << self
+ def anchor(...) = definition_class.anchor(...)
+
+ def required_owner_fields(...) = definition_class.required_owner_fields(...)
+
+ def schema(resource) = definition_for(resource).schema
+
+ def order(resource, ordering) = definition_for(resource).order(ordering)
+
+ def paged_from?(resource, cursor, ordering:)
+ definition_for(resource).paged_from?(cursor, ordering:)
+ end
+
+ def anchored_by?(resource, anchor_name:, ordering:)
+ definition_for(resource).anchored_by?(anchor_name:, ordering:)
+ end
+
+ def definition_for(resource)
+ definition_class.new(Declarations::Resource.new(resource))
+ end
+
+ private
+
+ def definition_class = const_get(:Definition)
+ end
+
+ delegate :schema,
+ :order,
+ :sort_key,
+ :paged_from?,
+ :anchored_by?,
+ :leading_sort_name,
+ :parse_cursor,
+ :valid_cursor?,
+ to: :definition
+
+ def initialize(resource)
+ @resource = resource
+ end
+
+ def collection?(value) = value.is_a?(Array)
+
+ private
+
+ attr_reader :resource
+
+ def definition = @definition ||= self.class.definition_for(resource)
+ end
+end
diff --git a/lib/json_api_kit/adapter/definition.rb b/lib/json_api_kit/adapter/definition.rb
new file mode 100644
index 00000000000..685334a7bbd
--- /dev/null
+++ b/lib/json_api_kit/adapter/definition.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Adapter
+ class Definition
+ def self.required_owner_fields(_name, owner_resource:) = []
+
+ def initialize(declarations)
+ @declarations = declarations
+ end
+
+ def valid_cursor?(_raw) = false
+
+ private
+
+ attr_reader :declarations
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record.rb b/lib/json_api_kit/adapters/active_record.rb
new file mode 100644
index 00000000000..450fff94d0f
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ def all(request, scoped_to: nil) = Query::Collection.new(resource, request, scoped_to:)
+
+ def find(request) = Query::Individual.new(resource, request)
+
+ def collection?(value) = super || value.is_a?(::ActiveRecord::Relation)
+
+ def scope_for(guardian)
+ return resource.scope_definition.call(guardian) if resource.scope_definition
+ resource.model.all
+ end
+
+ def record_for(id)
+ scope_for(resource.guardian).find_by(schema.primary_key => id) or raise NotFound
+ end
+
+ def filter(scope, name, value) = scope.where(name => value)
+
+ def anchors(guardian)
+ Declarations::Anchors.new(resource.anchor_declarations, guardian:)
+ end
+
+ def requested_page(request) = Page::Requested.from(request, adapter: self)
+
+ def related_records(relationship, owners:, owner_resource:)
+ RelatedRecords.new(resource, relationship, owners:, owner_resource:)
+ end
+
+ def related_scope(name, owner_id:)
+ schema.association(name.to_sym, [record_for(owner_id)]).related_scope
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/association.rb b/lib/json_api_kit/adapters/active_record/association.rb
new file mode 100644
index 00000000000..0772fc0d4b5
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/association.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/association/through.rb b/lib/json_api_kit/adapters/active_record/association/through.rb
new file mode 100644
index 00000000000..f085f28a985
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/association/through.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/columns.rb b/lib/json_api_kit/adapters/active_record/columns.rb
new file mode 100644
index 00000000000..9dc417f5362
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/columns.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class Columns
+ class << self
+ def all = All.new
+
+ def for_fields(fields, schema:)
+ return all if fields.all?
+ self.for(
+ fields.attributes.map { schema.column(it.name) unless it.requires_full_record? },
+ )
+ end
+
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/columns/all.rb b/lib/json_api_kit/adapters/active_record/columns/all.rb
new file mode 100644
index 00000000000..8c189a95f36
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/columns/all.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class Columns
+ class All < Columns
+ def initialize = super([])
+
+ def apply(scope) = scope
+
+ def with(*) = self
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/anchor.rb b/lib/json_api_kit/adapters/active_record/declarations/anchor.rb
new file mode 100644
index 00000000000..17b4f211e8d
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/anchor.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Declarations
+ class Anchor
+ class NoRow < BadRequest
+ def initialize(name, value)
+ @name = name
+ super("No record matches anchor #{name}=#{value.inspect}.")
+ end
+
+ def title = "No record matches the anchor"
+
+ def source = { parameter: "page[anchor][#{name}]" }
+
+ private
+
+ attr_reader :name
+ end
+
+ IDENTITY = "id"
+
+ class << self
+ def for(name, &condition)
+ return Computed.new(name, &condition) if condition
+ return Identity.new(name) if name.to_s == IDENTITY
+ Attribute.new(name)
+ end
+ end
+
+ attr_reader :name
+
+ def initialize(name)
+ @name = name.to_s
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute.rb b/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute.rb
new file mode 100644
index 00000000000..5d8e38ff979
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Declarations
+ class Anchor
+ class Attribute < Anchor
+ def accepts?(anchoring) = anchoring.single_value?
+
+ def locatable_in?(order) = order.leading.named?(name)
+
+ def locate(anchoring, scope:, order:, guardian:)
+ unless locatable_in?(order)
+ raise ArgumentError,
+ "Anchor #{name} does not match the leading sort key #{order.leading.name}."
+ end
+ order.enter(scope, at_or_after: order.leading.at_or_after(scope, anchoring.value))
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/anchor/computed.rb b/lib/json_api_kit/adapters/active_record/declarations/anchor/computed.rb
new file mode 100644
index 00000000000..f9b6bdd216b
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/anchor/computed.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Declarations
+ class Anchor
+ class Computed < Anchor
+ def initialize(name, &condition)
+ super(name)
+ @condition = condition
+ end
+
+ def accepts?(anchoring) = anchoring.without_value?
+
+ def locatable_in?(_order) = true
+
+ def locate(_anchoring, scope:, order:, guardian:) =
+ order.locate(condition.call(scope, guardian))
+
+ private
+
+ attr_reader :condition
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/anchor/identity.rb b/lib/json_api_kit/adapters/active_record/declarations/anchor/identity.rb
new file mode 100644
index 00000000000..8a57c0d9aa9
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/anchor/identity.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Declarations
+ class Anchor
+ class Identity < Anchor
+ def accepts?(anchoring) = anchoring.single_value?
+
+ def locatable_in?(_order) = true
+
+ def locate(anchoring, scope:, order:, guardian:)
+ order.locate(scope.where(scope.primary_key => anchoring.value)) or
+ raise NoRow.new(name, anchoring.value)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/anchors.rb b/lib/json_api_kit/adapters/active_record/declarations/anchors.rb
new file mode 100644
index 00000000000..46abfb2cf4a
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/anchors.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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(anchoring, scope:, order:, guardian:)
+ end
+
+ private
+
+ attr_reader :anchors, :guardian
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/sort.rb b/lib/json_api_kit/adapters/active_record/declarations/sort.rb
new file mode 100644
index 00000000000..6a0ce5281b1
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/sort.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/sort/related.rb b/lib/json_api_kit/adapters/active_record/declarations/sort/related.rb
new file mode 100644
index 00000000000..d5e8382b1a1
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/sort/related.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/declarations/sorts.rb b/lib/json_api_kit/adapters/active_record/declarations/sorts.rb
new file mode 100644
index 00000000000..146ef2659b9
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/declarations/sorts.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Declarations
+ class Sorts
+ delegate :fetch, to: :declarations
+ delegate :schema, :sort_key, to: :builder, private: true
+
+ def initialize(declarations, builder:, unique_by: nil)
+ @declarations = declarations
+ @builder = builder
+ @unique_by = Array(unique_by.presence || schema.primary_key)
+ end
+
+ def keyset(ordering) = Pagination::Keyset.new(keys(ordering))
+
+ private
+
+ attr_reader :declarations, :unique_by, :builder
+
+ def keys(ordering)
+ [
+ *ordering.map { |name, direction| fetch(name).key(builder:, direction:) },
+ *unique_keys(leading_direction(ordering)),
+ ]
+ end
+
+ def unique_keys(direction) = unique_by.map { sort_key(it, direction:) }
+
+ def leading_direction(ordering) = ordering.values.first || :asc
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/definition.rb b/lib/json_api_kit/adapters/active_record/definition.rb
new file mode 100644
index 00000000000..b882fa2f566
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/definition.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class Definition < Adapter::Definition
+ class << self
+ def anchor(...) = Declarations::Anchor.for(...)
+
+ def required_owner_fields(name, owner_resource:)
+ [owner_resource.schema.owner_key(name.to_sym)]
+ end
+ end
+
+ def schema = @schema ||= Schema.new(model)
+
+ def order(ordering) = Pagination::Order.new(sorts.keyset(ordering), type:)
+
+ def sort_key(name, direction:, **options)
+ Declarations::Sort.for(name, **options).key(schema:, direction:)
+ end
+
+ def parse_cursor(raw) = Pagination::Cursor.parse(raw)
+
+ def valid_cursor?(raw) = Pagination::Cursor.valid?(raw)
+
+ def paged_from?(cursor, ordering:) = order(ordering).compatible_with?(cursor:)
+
+ def anchored_by?(anchor_name:, ordering:)
+ anchor_declarations
+ .detect { it.name == anchor_name.to_s }
+ .then { |anchor| anchor.nil? || anchor.locatable_in?(order(ordering)) }
+ end
+
+ def leading_sort_name(ordering) = order(ordering).leading.name.to_s
+
+ private
+
+ delegate :model, :type, :unique_key, :anchor_declarations, to: :declarations, private: true
+
+ def sorts
+ @sorts ||=
+ Declarations::Sorts.new(declarations.sorts, unique_by: unique_key, builder: self)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/joins.rb b/lib/json_api_kit/adapters/active_record/joins.rb
new file mode 100644
index 00000000000..96a1b450349
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/joins.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/per_owner.rb b/lib/json_api_kit/adapters/active_record/page/per_owner.rb
new file mode 100644
index 00000000000..1c7bb53286a
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/per_owner.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/requested.rb b/lib/json_api_kit/adapters/active_record/page/requested.rb
new file mode 100644
index 00000000000..f221be87dfc
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/requested.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Page
+ class Requested
+ class << self
+ def from(request, adapter:)
+ self.for(
+ **request.page.except(:item_cursors, :anchor).compact,
+ after: request.page[:after].try { adapter.parse_cursor(it) },
+ before: request.page[:before].try { adapter.parse_cursor(it) },
+ anchoring: request.anchoring,
+ )
+ end
+
+ def 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
+ end
+
+ def initialize(size: nil)
+ @size = size
+ end
+
+ private
+
+ attr_reader :size
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/requested/after.rb b/lib/json_api_kit/adapters/active_record/page/requested/after.rb
new file mode 100644
index 00000000000..ecb8659f063
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/requested/after.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/requested/around.rb b/lib/json_api_kit/adapters/active_record/page/requested/around.rb
new file mode 100644
index 00000000000..e75a3c7513e
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/requested/around.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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.without_value?
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/requested/before.rb b/lib/json_api_kit/adapters/active_record/page/requested/before.rb
new file mode 100644
index 00000000000..9503da66c67
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/requested/before.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/requested/first.rb b/lib/json_api_kit/adapters/active_record/page/requested/first.rb
new file mode 100644
index 00000000000..9a4124f6043
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/requested/first.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/page/window.rb b/lib/json_api_kit/adapters/active_record/page/window.rb
new file mode 100644
index 00000000000..a0b5b9d76fc
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/page/window.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/around.rb b/lib/json_api_kit/adapters/active_record/pagination/around.rb
new file mode 100644
index 00000000000..cb818972519
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/around.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/cursor.rb b/lib/json_api_kit/adapters/active_record/pagination/cursor.rb
new file mode 100644
index 00000000000..5b965bb1d3c
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/cursor.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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, "Decoded cursor must be a JSON array." unless values.is_a?(Array)
+ new(values.map { coerce(it) })
+ rescue JSON::ParserError
+ raise ArgumentError, "Decoded cursor contains invalid JSON."
+ 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, "Unsupported cursor value type: #{value.class}."
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/direction.rb b/lib/json_api_kit/adapters/active_record/pagination/direction.rb
new file mode 100644
index 00000000000..b9cdc43f7d7
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/direction.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Pagination
+ class Direction
+ def self.for(direction)
+ case direction
+ when :asc
+ Ascending.new
+ when :desc
+ Descending.new
+ else
+ raise ArgumentError, "Unknown sort direction: #{direction.inspect}."
+ end
+ end
+
+ def ==(other) = other.instance_of?(self.class)
+
+ alias eql? ==
+
+ def hash = self.class.hash
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/direction/ascending.rb b/lib/json_api_kit/adapters/active_record/pagination/direction/ascending.rb
new file mode 100644
index 00000000000..6bfdec88f3b
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/direction/ascending.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/direction/descending.rb b/lib/json_api_kit/adapters/active_record/pagination/direction/descending.rb
new file mode 100644
index 00000000000..c48c2675ae7
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/direction/descending.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/empty_page.rb b/lib/json_api_kit/adapters/active_record/pagination/empty_page.rb
new file mode 100644
index 00000000000..cc902731523
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/empty_page.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Pagination
+ class EmptyPage
+ def rows = []
+
+ def next = nil
+
+ def previous = nil
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/keyset.rb b/lib/json_api_kit/adapters/active_record/pagination/keyset.rb
new file mode 100644
index 00000000000..f318d1a8885
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/keyset.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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, "Sort order must contain 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/keyset/key.rb b/lib/json_api_kit/adapters/active_record/pagination/keyset/key.rb
new file mode 100644
index 00000000000..a3d570afb77
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/keyset/key.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/nulls.rb b/lib/json_api_kit/adapters/active_record/pagination/nulls.rb
new file mode 100644
index 00000000000..372318f59d7
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/nulls.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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 null placement: #{placement.inspect}."
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/nulls/first.rb b/lib/json_api_kit/adapters/active_record/pagination/nulls/first.rb
new file mode 100644
index 00000000000..392fd753f5b
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/nulls/first.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/nulls/last.rb b/lib/json_api_kit/adapters/active_record/pagination/nulls/last.rb
new file mode 100644
index 00000000000..a18a68552b7
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/nulls/last.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/nulls/undeclared.rb b/lib/json_api_kit/adapters/active_record/pagination/nulls/undeclared.rb
new file mode 100644
index 00000000000..bf3b03ce985
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/nulls/undeclared.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/numbered_rows.rb b/lib/json_api_kit/adapters/active_record/pagination/numbered_rows.rb
new file mode 100644
index 00000000000..a86cc2d9f83
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/numbered_rows.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/order.rb b/lib/json_api_kit/adapters/active_record/pagination/order.rb
new file mode 100644
index 00000000000..a6fd01d328e
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/order.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/order/position.rb b/lib/json_api_kit/adapters/active_record/pagination/order/position.rb
new file mode 100644
index 00000000000..cbde42ef985
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/order/position.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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, "Cursor does not match the requested resource and sort order."
+ end
+ new(segment: order.fetch(segment_id), values:)
+ end
+
+ def initialize(segment:, values:)
+ unless segment.compatible_with?(values)
+ raise ArgumentError,
+ "Incorrect number of values for this order segment: " \
+ "expected #{segment.keyset.keys.size}, received #{values.size}."
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/order/segment.rb b/lib/json_api_kit/adapters/active_record/pagination/order/segment.rb
new file mode 100644
index 00000000000..44e917d3622
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/order/segment.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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 do
+ it.narrowed_by(keyset.null_condition)
+ end
+ 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))
+ end
+
+ private
+
+ attr_reader :condition
+
+ def condition_after(other) = ->(scope) { condition.call(other.call(scope)) }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/order/segments.rb b/lib/json_api_kit/adapters/active_record/pagination/order/segments.rb
new file mode 100644
index 00000000000..a67a6f0c543
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/order/segments.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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, "Unknown order 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/page_per_owner.rb b/lib/json_api_kit/adapters/active_record/pagination/page_per_owner.rb
new file mode 100644
index 00000000000..c9debc03331
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/page_per_owner.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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,
+ "Cannot paginate relationships using nullable sort key #{order.leading.name}. " \
+ "Declare a default sort on a column that cannot be null."
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/paginator.rb b/lib/json_api_kit/adapters/active_record/pagination/paginator.rb
new file mode 100644
index 00000000000..060893be100
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/paginator.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Pagination
+ class Paginator
+ def self.for(scope, order:, size:, after: nil, before: nil)
+ raise ArgumentError, "Cannot specify both before and after cursors." 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/paginator/backwards.rb b/lib/json_api_kit/adapters/active_record/pagination/paginator/backwards.rb
new file mode 100644
index 00000000000..3d2d9dd5586
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/paginator/backwards.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/paginator/forwards.rb b/lib/json_api_kit/adapters/active_record/pagination/paginator/forwards.rb
new file mode 100644
index 00000000000..cdcb467df84
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/paginator/forwards.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Pagination
+ class Paginator
+ class Forwards < Paginator
+ def next = page_ahead
+
+ def previous = page_behind
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/predicate.rb b/lib/json_api_kit/adapters/active_record/pagination/predicate.rb
new file mode 100644
index 00000000000..6c54e96e0a1
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/predicate.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ module Pagination
+ class Predicate
+ def initialize(keyset, values)
+ if keyset.split?
+ raise ArgumentError, "Pagination predicates require a single order segment."
+ end
+
+ @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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/predicate/term.rb b/lib/json_api_kit/adapters/active_record/pagination/predicate/term.rb
new file mode 100644
index 00000000000..079ca1101c9
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/predicate/term.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null.rb b/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null.rb
new file mode 100644
index 00000000000..1e7686ccc27
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/row.rb b/lib/json_api_kit/adapters/active_record/pagination/row.rb
new file mode 100644
index 00000000000..27f12677adc
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/row.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/scan.rb b/lib/json_api_kit/adapters/active_record/pagination/scan.rb
new file mode 100644
index 00000000000..6293bc64269
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/scan.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+
+ def next_in(order)
+ return if truncated?
+
+ order
+ .after(segment)
+ .first
+ .try { self.class.new(scope, segment: it, size: size - rows.size) }
+ end
+
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/pagination/window.rb b/lib/json_api_kit/adapters/active_record/pagination/window.rb
new file mode 100644
index 00000000000..ce825d69042
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/pagination/window.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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 ||= Enumerator.produce(first_scan) { it.next_in(order) }.take_while { it }
+ end
+
+ def first_scan = Scan.new(scope, segment: starting_segment, size:, after: after&.values)
+
+ def starting_segment = after&.segment || order.first
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/query.rb b/lib/json_api_kit/adapters/active_record/query.rb
new file mode 100644
index 00000000000..aa10830eecd
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/query.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class Query < JsonApiKit::Query
+ def initialize(resource, request, scoped_to: nil)
+ super(resource, request)
+ @scoped_to = scoped_to
+ end
+
+ def rows = page.rows
+
+ private
+
+ attr_reader :scoped_to
+
+ delegate :adapter, :schema, to: :resource, private: true
+
+ def page
+ @page ||=
+ scoping.page(adapter.requested_page(request)).paginate(scope, order:, limits:, anchors:)
+ end
+
+ 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
+ Columns.for_fields(fields, schema:).with(
+ *order.columns,
+ *owner_keys,
+ *scoping.pairing_keys,
+ schema.primary_key,
+ )
+ end
+
+ def owner_keys
+ relationships.flat_map do |relationship|
+ relationship.resource.adapter.required_owner_fields(
+ relationship.name,
+ owner_resource: resource,
+ )
+ end
+ end
+
+ def filtered_scope = resource.apply_filters(available_scope, request.filtering)
+
+ def available_scope = resource.scope_for(guardian)
+
+ def order = @order ||= resource.order(request.ordering)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/query/collection.rb b/lib/json_api_kit/adapters/active_record/query/collection.rb
new file mode 100644
index 00000000000..1c80abd74a0
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/query/collection.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/query/individual.rb b/lib/json_api_kit/adapters/active_record/query/individual.rb
new file mode 100644
index 00000000000..e0e41b7cd1f
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/query/individual.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class Query
+ class Individual < Query
+ def record
+ records.first or raise NotFound
+ end
+
+ private
+
+ def available_scope = super.where(schema.primary_key => request.id)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/reflection.rb b/lib/json_api_kit/adapters/active_record/reflection.rb
new file mode 100644
index 00000000000..5cdb758c1bc
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/reflection.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/reflection/through.rb b/lib/json_api_kit/adapters/active_record/reflection/through.rb
new file mode 100644
index 00000000000..3f892f54c78
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/reflection/through.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/related_records.rb b/lib/json_api_kit/adapters/active_record/related_records.rb
new file mode 100644
index 00000000000..f3cb1c70caf
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/related_records.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ class RelatedRecords
+ def initialize(resource, relationship, owners:, owner_resource:)
+ @resource = resource
+ @relationship = relationship
+ @owners = owners
+ @owner_resource = owner_resource
+ end
+
+ def scope = association.related_scope
+
+ def records_by_owner(params) = pair(records(params))
+
+ private
+
+ attr_reader :resource, :relationship, :owners, :owner_resource
+
+ def records(params) = resource.all(params, scoped_to: association.to_scoping).records
+
+ def pair(records)
+ association.pair(records.map(&:record)).transform_values { records.fetch_all(it) }
+ end
+
+ def association
+ @association ||= owner_resource.schema.association(relationship.name.to_sym, owners)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/schema.rb b/lib/json_api_kit/adapters/active_record/schema.rb
new file mode 100644
index 00000000000..03319989ae8
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/schema.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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} has 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
+ end
+end
diff --git a/lib/json_api_kit/adapters/active_record/scoping.rb b/lib/json_api_kit/adapters/active_record/scoping.rb
new file mode 100644
index 00000000000..4a08aad8225
--- /dev/null
+++ b/lib/json_api_kit/adapters/active_record/scoping.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Adapters
+ class ActiveRecord < Adapter
+ 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
+ end
+end
diff --git a/lib/json_api_kit/association.rb b/lib/json_api_kit/association.rb
deleted file mode 100644
index 2a44a7721c4..00000000000
--- a/lib/json_api_kit/association.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-# 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
deleted file mode 100644
index 0bffdf8fb94..00000000000
--- a/lib/json_api_kit/association/through.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# 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/columns.rb b/lib/json_api_kit/columns.rb
deleted file mode 100644
index 4559a72bc0d..00000000000
--- a/lib/json_api_kit/columns.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# 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
deleted file mode 100644
index a526d1bba71..00000000000
--- a/lib/json_api_kit/columns/all.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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
deleted file mode 100644
index 2a0ce1b8e5b..00000000000
--- a/lib/json_api_kit/declarations/anchor.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-# 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"
-
- class << self
- def for(name, &condition)
- return Computed.new(name, &condition) if condition
- return Identity.new(name) if name.to_s == IDENTITY
- Attribute.new(name)
- end
- end
-
- attr_reader :name
-
- def initialize(name)
- @name = name.to_s
- end
- end
- end
-end
diff --git a/lib/json_api_kit/declarations/anchor/attribute.rb b/lib/json_api_kit/declarations/anchor/attribute.rb
deleted file mode 100644
index c7c52592884..00000000000
--- a/lib/json_api_kit/declarations/anchor/attribute.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-# frozen_string_literal: true
-
-module JsonApiKit
- module Declarations
- class Anchor
- class Attribute < Anchor
- def accepts?(anchoring) = anchoring.single_value?
-
- def locatable_in?(order) = order.leading.named?(name)
-
- def locate(anchoring, scope:, order:, guardian:)
- unless locatable_in?(order)
- raise ArgumentError,
- "The anchor is #{name}, but this request sorts by #{order.leading}."
- end
- order.enter(scope, at_or_after: order.leading.at_or_after(scope, anchoring.value))
- end
- end
- end
- end
-end
diff --git a/lib/json_api_kit/declarations/anchor/computed.rb b/lib/json_api_kit/declarations/anchor/computed.rb
deleted file mode 100644
index 0791479589a..00000000000
--- a/lib/json_api_kit/declarations/anchor/computed.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# frozen_string_literal: true
-
-module JsonApiKit
- module Declarations
- class Anchor
- class Computed < Anchor
- def initialize(name, &condition)
- super(name)
- @condition = condition
- end
-
- def accepts?(anchoring) = anchoring.without_value?
-
- def locatable_in?(_order) = true
-
- def locate(_anchoring, scope:, order:, guardian:) =
- order.locate(condition.call(scope, guardian))
-
- private
-
- attr_reader :condition
- end
- end
- end
-end
diff --git a/lib/json_api_kit/declarations/anchor/identity.rb b/lib/json_api_kit/declarations/anchor/identity.rb
deleted file mode 100644
index 4a143d9141b..00000000000
--- a/lib/json_api_kit/declarations/anchor/identity.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-# frozen_string_literal: true
-
-module JsonApiKit
- module Declarations
- class Anchor
- class Identity < Anchor
- def accepts?(anchoring) = anchoring.single_value?
-
- def locatable_in?(_order) = true
-
- def locate(anchoring, scope:, order:, guardian:)
- order.locate(scope.where(scope.primary_key => anchoring.value)) or
- raise NoRow.new(name, anchoring.value)
- end
- end
- end
- end
-end
diff --git a/lib/json_api_kit/declarations/anchors.rb b/lib/json_api_kit/declarations/anchors.rb
deleted file mode 100644
index 7aad32381e3..00000000000
--- a/lib/json_api_kit/declarations/anchors.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# 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(anchoring, scope:, 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
index 6034b26eee8..51c9c4c2f27 100644
--- a/lib/json_api_kit/declarations/attribute.rb
+++ b/lib/json_api_kit/declarations/attribute.rb
@@ -23,10 +23,7 @@ module JsonApiKit
record.public_send(name)
end
- def column_for(schema)
- return if value || readable.per_record?
- schema.column(name)
- end
+ def requires_full_record? = value.present? || readable.per_record?
private
diff --git a/lib/json_api_kit/declarations/attributes.rb b/lib/json_api_kit/declarations/attributes.rb
index 1159dcc7416..ac82963c3aa 100644
--- a/lib/json_api_kit/declarations/attributes.rb
+++ b/lib/json_api_kit/declarations/attributes.rb
@@ -3,10 +3,13 @@
module JsonApiKit
module Declarations
class Attributes
- def initialize(attributes, guardian:, schema:, type:)
+ include Enumerable
+
+ delegate :each, to: :attributes
+
+ def initialize(attributes, guardian:, type:)
@attributes = attributes
@guardian = guardian
- @schema = schema
@type = type
@field_names = {}
end
@@ -15,11 +18,9 @@ module JsonApiKit
def values_for(record) = readable(record).to_h { [field_name(it), it.value_for(record)] }
- def columns = Columns.for(attributes.map { it.column_for(schema) })
-
private
- attr_reader :attributes, :guardian, :schema, :type, :field_names
+ attr_reader :attributes, :guardian, :type, :field_names
def readable(record) = attributes.select { it.readable_for?(guardian, record) }
diff --git a/lib/json_api_kit/declarations/fields.rb b/lib/json_api_kit/declarations/fields.rb
index 047d31dab38..12217a998f6 100644
--- a/lib/json_api_kit/declarations/fields.rb
+++ b/lib/json_api_kit/declarations/fields.rb
@@ -12,27 +12,26 @@ module JsonApiKit
new(names, **declarations)
end
- def initialize(names, guardian:, attributes:, relationships:, schema:, type:)
+ def initialize(names, guardian:, attributes:, relationships:, type:)
@names = names
@guardian = guardian
@declared_attributes = attributes
@declared_relationships = relationships
- @schema = schema
@type = type
verify_field_names
end
def attributes
- @attributes ||= Attributes.new(pick(declared_attributes), guardian:, schema:, type:)
+ @attributes ||= Attributes.new(pick(declared_attributes), guardian:, type:)
end
def relationships = Relationships.new(pick(declared_relationships))
- def columns = attributes.columns
+ def all? = false
private
- attr_reader :names, :guardian, :declared_attributes, :declared_relationships, :schema, :type
+ attr_reader :names, :guardian, :declared_attributes, :declared_relationships, :type
def pick(fields) = readable(fields).select { names.include?(it.name) }
@@ -50,13 +49,13 @@ module JsonApiKit
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"
+ raise Collision, "Cannot declare reserved field names: #{reserved_names.join(", ")}."
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"
+ raise Collision, "Duplicate field names: #{repeated_names.join(", ")}."
end
end
end
diff --git a/lib/json_api_kit/declarations/fields/all.rb b/lib/json_api_kit/declarations/fields/all.rb
index 798d1cb7053..80f86d9870f 100644
--- a/lib/json_api_kit/declarations/fields/all.rb
+++ b/lib/json_api_kit/declarations/fields/all.rb
@@ -6,7 +6,7 @@ module JsonApiKit
class All < Fields
def initialize(**declarations) = super(nil, **declarations)
- def columns = Columns.all
+ def all? = true
private
diff --git a/lib/json_api_kit/declarations/filter.rb b/lib/json_api_kit/declarations/filter.rb
index 7cc542ab9d5..02bacbca1a1 100644
--- a/lib/json_api_kit/declarations/filter.rb
+++ b/lib/json_api_kit/declarations/filter.rb
@@ -7,10 +7,13 @@ module JsonApiKit
def initialize(name, &condition)
@name = name.to_s
- @condition = condition || Equality.new(@name)
+ @condition = condition
end
- def apply(scope, value) = condition.call(scope, value)
+ def apply(scope, value, adapter:)
+ return condition.call(scope, value) if condition
+ adapter.filter(scope, name, value)
+ end
private
diff --git a/lib/json_api_kit/declarations/filter/equality.rb b/lib/json_api_kit/declarations/filter/equality.rb
deleted file mode 100644
index 6e1177bdece..00000000000
--- a/lib/json_api_kit/declarations/filter/equality.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# 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
index eb43a95fd67..cfa238944e8 100644
--- a/lib/json_api_kit/declarations/filters.rb
+++ b/lib/json_api_kit/declarations/filters.rb
@@ -13,9 +13,11 @@ module JsonApiKit
def with(additional_filters) = self.class.new(declarations.chain(additional_filters))
- def apply(scope, filtering = {})
+ def apply(scope, filtering = {}, adapter:)
return scope if filtering.blank?
- filtering.reduce(scope) { |narrowed, (name, value)| fetch(name).apply(narrowed, value) }
+ filtering.reduce(scope) do |narrowed, (name, value)|
+ fetch(name).apply(narrowed, value, adapter:)
+ end
end
private
diff --git a/lib/json_api_kit/declarations/relationship.rb b/lib/json_api_kit/declarations/relationship.rb
index 6a7189b236c..065f3cd21ed 100644
--- a/lib/json_api_kit/declarations/relationship.rb
+++ b/lib/json_api_kit/declarations/relationship.rb
@@ -16,10 +16,6 @@ module JsonApiKit
verify_readable_block
end
- def listing(params, guardian:, scoped_to:, edition:)
- resource.all(params, guardian:, scoped_to:, edition:)
- end
-
def resolves?(path) = resource.resolves?(path)
private
@@ -29,7 +25,7 @@ module JsonApiKit
def verify_readable_block
return unless readable.per_record?
raise UnsupportedRule,
- "#{name}: having both a guardian and a record for a relationship isn’t supported"
+ "#{name}: relationship readability blocks cannot accept a record argument."
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
index 725783b43c9..7a4cc53a849 100644
--- a/lib/json_api_kit/declarations/relationship/to_many.rb
+++ b/lib/json_api_kit/declarations/relationship/to_many.rb
@@ -4,8 +4,6 @@ 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
diff --git a/lib/json_api_kit/declarations/relationship/to_one.rb b/lib/json_api_kit/declarations/relationship/to_one.rb
index 6f6dd5be0fe..31bfeaf8256 100644
--- a/lib/json_api_kit/declarations/relationship/to_one.rb
+++ b/lib/json_api_kit/declarations/relationship/to_one.rb
@@ -4,8 +4,6 @@ module JsonApiKit
module Declarations
class Relationship
class ToOne < Relationship
- def scoping(association) = association.to_scoping
-
def linkage(records) = Linkage::ToOne.new(records)
end
end
diff --git a/lib/json_api_kit/declarations/resource.rb b/lib/json_api_kit/declarations/resource.rb
new file mode 100644
index 00000000000..d90c00aa955
--- /dev/null
+++ b/lib/json_api_kit/declarations/resource.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Resource
+ delegate :sorts, :unique_key, :anchor_declarations, to: :resource
+
+ def initialize(resource)
+ @resource = resource
+ end
+
+ def model = resource.model
+
+ def type = resource.type
+
+ private
+
+ attr_reader :resource
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/sort.rb b/lib/json_api_kit/declarations/sort.rb
index f84d2d517c3..0bf2f587f73 100644
--- a/lib/json_api_kit/declarations/sort.rb
+++ b/lib/json_api_kit/declarations/sort.rb
@@ -3,46 +3,26 @@
module JsonApiKit
module Declarations
class Sort
- SEPARATOR = "."
-
- def self.for(name, ...)
- return Related.new(name, ...) if name.to_s.include?(SEPARATOR)
- new(name, ...)
+ class << self
+ def verify_direction!(direction)
+ unless direction.in?(%i[asc desc])
+ raise ArgumentError, "Unknown sort direction: #{direction.inspect}."
+ end
+ end
end
attr_reader :name
- def initialize(name, column: nil, sql: nil, joins: [], nulls: nil)
+ def initialize(name, **options)
@name = name.to_s
- @column = column
- @sql = sql
- @joins = joins
- @nulls = nulls
+ @options = options
end
- def key(schema:, direction:)
- Pagination::Keyset::Key.new(
- attribute,
- model: schema.model,
- direction:,
- sql: sql_for(schema),
- joins:,
- nulls: placement(schema),
- )
- end
+ def key(builder:, direction:) = builder.sort_key(name, direction:, **options)
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
+ attr_reader :options
end
end
end
diff --git a/lib/json_api_kit/declarations/sort/related.rb b/lib/json_api_kit/declarations/sort/related.rb
deleted file mode 100644
index 8599aba9e33..00000000000
--- a/lib/json_api_kit/declarations/sort/related.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# 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
index 75f96f311bc..95a4c36d703 100644
--- a/lib/json_api_kit/declarations/sorts.rb
+++ b/lib/json_api_kit/declarations/sorts.rb
@@ -5,36 +5,21 @@ module JsonApiKit
class Sorts
delegate :fetch, to: :sorts
- def initialize(declarations, schema:, unique_by: nil)
+ def initialize(declarations)
@declarations = declarations
- @schema = schema
- @unique_by = Array(unique_by.presence || schema.primary_key)
end
def names = sorts.keys
def with(additional_sorts)
- self.class.new(declarations.chain(additional_sorts), schema:, unique_by:)
+ self.class.new(declarations.chain(additional_sorts))
end
- def keyset(ordering) = Pagination::Keyset.new(keys(ordering))
-
private
- attr_reader :declarations, :schema, :unique_by
+ attr_reader :declarations
def sorts = @sorts ||= declarations.index_by(&:name)
-
- 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/default_sort.rb b/lib/json_api_kit/default_sort.rb
index a19c2c2598f..a891fde25df 100644
--- a/lib/json_api_kit/default_sort.rb
+++ b/lib/json_api_kit/default_sort.rb
@@ -7,7 +7,7 @@ module JsonApiKit
def initialize(type, ordering)
@type = type.to_s
@ordering = ordering.to_h.transform_keys(&:to_s).freeze
- @ordering.each_value { Pagination::Direction.for(it) }
+ @ordering.each_value { Declarations::Sort.verify_direction!(it) }
end
def convert_names(&conversion)
diff --git a/lib/json_api_kit/document.rb b/lib/json_api_kit/document.rb
index e0c7d6c1e36..8147c85882c 100644
--- a/lib/json_api_kit/document.rb
+++ b/lib/json_api_kit/document.rb
@@ -7,15 +7,21 @@ module JsonApiKit
case value
when Document, Errors
value
- when Array, ActiveRecord::Relation
- Collection.from(value, **yield)
else
- Individual.from(value, **yield)
+ from_resource(value, **yield)
end
end
private
+ def from_resource(value, resource:, input:, client:)
+ if resource.adapter.collection?(value)
+ Collection.from(value, resource:, input:, client:)
+ else
+ Individual.from(value, resource:, input:, client:)
+ end
+ end
+
def from_records(records, resource:, input:, client:)
request = Request.new(input.to_h, guardian: client.guardian, edition: client.edition)
assemble(
@@ -24,7 +30,13 @@ module JsonApiKit
end
def build(raw, resource:, client:)
- resource = resource.new(guardian: client.guardian, edition: client.edition)
+ resource =
+ case resource
+ when Class
+ resource.new(guardian: client.guardian, edition: client.edition)
+ else
+ resource
+ end
input = input_class.new(raw, resource:, edition: client.edition)
return Errors.new(*input.refusals) if input.invalid?
assemble(new(yield(input.to_h, resource), client:, fieldsets: input.fieldsets))
diff --git a/lib/json_api_kit/joins.rb b/lib/json_api_kit/joins.rb
deleted file mode 100644
index 8c3e18acc5f..00000000000
--- a/lib/json_api_kit/joins.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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/page/per_owner.rb b/lib/json_api_kit/page/per_owner.rb
deleted file mode 100644
index 8f8335a6f35..00000000000
--- a/lib/json_api_kit/page/per_owner.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# 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
deleted file mode 100644
index b800e45d15e..00000000000
--- a/lib/json_api_kit/page/requested.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# 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
deleted file mode 100644
index 31194c46b54..00000000000
--- a/lib/json_api_kit/page/requested/after.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# 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
deleted file mode 100644
index 4e323a9454d..00000000000
--- a/lib/json_api_kit/page/requested/around.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-# 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.without_value?
- 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
deleted file mode 100644
index 4eb6a239630..00000000000
--- a/lib/json_api_kit/page/requested/before.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# 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
deleted file mode 100644
index d2974357216..00000000000
--- a/lib/json_api_kit/page/requested/first.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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
deleted file mode 100644
index dcb00f9fb1f..00000000000
--- a/lib/json_api_kit/page/window.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# 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
deleted file mode 100644
index acded996899..00000000000
--- a/lib/json_api_kit/pagination/around.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-# 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
deleted file mode 100644
index 0cd7d9286b2..00000000000
--- a/lib/json_api_kit/pagination/cursor.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-# 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
deleted file mode 100644
index ced75075a80..00000000000
--- a/lib/json_api_kit/pagination/direction.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-# frozen_string_literal: true
-
-module JsonApiKit
- module Pagination
- class Direction
- def self.for(direction)
- case direction
- 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
deleted file mode 100644
index 00a386638a3..00000000000
--- a/lib/json_api_kit/pagination/direction/ascending.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# 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
deleted file mode 100644
index 1457035cd53..00000000000
--- a/lib/json_api_kit/pagination/direction/descending.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# 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
deleted file mode 100644
index c653c5d79bb..00000000000
--- a/lib/json_api_kit/pagination/empty_page.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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
deleted file mode 100644
index 955622a3e95..00000000000
--- a/lib/json_api_kit/pagination/keyset.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-# 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
deleted file mode 100644
index dffcc26d4cf..00000000000
--- a/lib/json_api_kit/pagination/keyset/key.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-# 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
deleted file mode 100644
index 1eebaca4561..00000000000
--- a/lib/json_api_kit/pagination/nulls.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# 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
deleted file mode 100644
index b01394de43f..00000000000
--- a/lib/json_api_kit/pagination/nulls/first.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-# 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
deleted file mode 100644
index 236d8bacce8..00000000000
--- a/lib/json_api_kit/pagination/nulls/last.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-# 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
deleted file mode 100644
index a208a78d631..00000000000
--- a/lib/json_api_kit/pagination/nulls/undeclared.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-# 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
deleted file mode 100644
index b146150dd57..00000000000
--- a/lib/json_api_kit/pagination/numbered_rows.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-# 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
deleted file mode 100644
index c1253b297c5..00000000000
--- a/lib/json_api_kit/pagination/order.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-# 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
deleted file mode 100644
index 7470113e664..00000000000
--- a/lib/json_api_kit/pagination/order/position.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# 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
deleted file mode 100644
index 35808feafb9..00000000000
--- a/lib/json_api_kit/pagination/order/segment.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-# 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))
- end
-
- 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
deleted file mode 100644
index b658737c76e..00000000000
--- a/lib/json_api_kit/pagination/order/segments.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-# 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
deleted file mode 100644
index 067cf679e64..00000000000
--- a/lib/json_api_kit/pagination/page_per_owner.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-# 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
deleted file mode 100644
index decc82f9348..00000000000
--- a/lib/json_api_kit/pagination/paginator.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-# 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
deleted file mode 100644
index 3587c8ce1a2..00000000000
--- a/lib/json_api_kit/pagination/paginator/backwards.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# 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
deleted file mode 100644
index fdd1810912f..00000000000
--- a/lib/json_api_kit/pagination/paginator/forwards.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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
deleted file mode 100644
index aee839ebcb7..00000000000
--- a/lib/json_api_kit/pagination/predicate.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-# 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
deleted file mode 100644
index f2ec3b9ffec..00000000000
--- a/lib/json_api_kit/pagination/predicate/term.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-# 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
deleted file mode 100644
index fe9e53e9990..00000000000
--- a/lib/json_api_kit/pagination/predicate/term/null.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-# 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
deleted file mode 100644
index 343134133f4..00000000000
--- a/lib/json_api_kit/pagination/row.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# 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
deleted file mode 100644
index 9321e7aa8b1..00000000000
--- a/lib/json_api_kit/pagination/scan.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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
deleted file mode 100644
index 1b80f331cc9..00000000000
--- a/lib/json_api_kit/pagination/window.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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/query.rb b/lib/json_api_kit/query.rb
index 1e5177512bf..c0e0580186c 100644
--- a/lib/json_api_kit/query.rb
+++ b/lib/json_api_kit/query.rb
@@ -2,14 +2,11 @@
module JsonApiKit
class Query
- def initialize(resource, request, scoped_to: nil)
+ def initialize(resource, request)
@resource = resource
@request = request
- @scoped_to = scoped_to
end
- def rows = page.rows
-
def records
@records ||=
Records.new(
@@ -25,45 +22,19 @@ module JsonApiKit
private
- attr_reader :resource, :request, :scoped_to
+ attr_reader :resource, :request
delegate :guardian, to: :request, private: true
delegate :type, :namespace, to: :resource, 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[type], guardian:)
def sideloads
- @sideloads ||= Sideloads.for(relationships, paths:, rows:, request:, schema:)
+ @sideloads ||= Sideloads.for(relationships, paths:, rows:, request:, resource:)
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
deleted file mode 100644
index 0bd5cc3be46..00000000000
--- a/lib/json_api_kit/query/collection.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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
deleted file mode 100644
index dee13ec7df9..00000000000
--- a/lib/json_api_kit/query/individual.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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/reflection.rb b/lib/json_api_kit/reflection.rb
deleted file mode 100644
index 54d574564f5..00000000000
--- a/lib/json_api_kit/reflection.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-# 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
deleted file mode 100644
index da1abc4cf58..00000000000
--- a/lib/json_api_kit/reflection/through.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-# 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/relationship.rb b/lib/json_api_kit/relationship.rb
index 4e96f71ea2e..a8eb8a01e01 100644
--- a/lib/json_api_kit/relationship.rb
+++ b/lib/json_api_kit/relationship.rb
@@ -8,9 +8,17 @@ module JsonApiKit
@owner_resource = resource
end
- delegate :resource, to: :declaration
+ def resource
+ @resource ||= declaration.resource.new(guardian:, edition: owner_resource.edition)
+ end
- def scope = owner_resource.related_scope(declaration.name, owner_id:)
+ def scope
+ resource.related_records(
+ declaration,
+ owners: [owner_resource.record_for(owner_id)],
+ owner_resource:,
+ ).scope
+ end
private
diff --git a/lib/json_api_kit/request.rb b/lib/json_api_kit/request.rb
index 3b4a7289786..4e3a17b6a9e 100644
--- a/lib/json_api_kit/request.rb
+++ b/lib/json_api_kit/request.rb
@@ -24,7 +24,7 @@ module JsonApiKit
def for_sideload(paths) = { fields:, include: paths }
- def page = @page ||= Page::Requested.for(anchoring:, **paging)
+ def page = page_params
def anchoring = @anchoring ||= Anchoring.for(page_params[:anchor])
@@ -33,17 +33,5 @@ module JsonApiKit
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
index d3a63fbd509..4fbed53b7e7 100644
--- a/lib/json_api_kit/request/collection.rb
+++ b/lib/json_api_kit/request/collection.rb
@@ -3,7 +3,6 @@
module JsonApiKit
class Request
class Collection < Request
- def scope(from:) = from
end
end
end
diff --git a/lib/json_api_kit/request/contract/paging.rb b/lib/json_api_kit/request/contract/paging.rb
index 617a79d4a39..c44f04522d8 100644
--- a/lib/json_api_kit/request/contract/paging.rb
+++ b/lib/json_api_kit/request/contract/paging.rb
@@ -77,8 +77,8 @@ module JsonApiKit
def cursors
raw_cursors
- .select { |_, raw| Pagination::Cursor.valid?(raw) }
- .transform_values { Pagination::Cursor.parse(it) }
+ .select { |_, raw| resource.valid_cursor?(raw) }
+ .transform_values { resource.parse_cursor(it) }
end
def resource = options[:resource]
@@ -136,16 +136,14 @@ module JsonApiKit
end
def check_anchor_ordering
+ return unless anchoring.name.in?(resource.anchor_names)
return if resource.anchored_by?(anchor_name: anchoring.name, ordering:)
errors.add(
:anchor,
:not_the_sort,
name: Name::Anchor.new(value: anchoring.name, type: resource.type),
key:
- Name::Sort.new(
- value: resource.order(ordering).leading.name.to_s,
- type: resource.type,
- ),
+ Name::Sort.new(value: resource.leading_sort_name(ordering), type: resource.type),
message: "not the sort",
)
end
diff --git a/lib/json_api_kit/request/individual.rb b/lib/json_api_kit/request/individual.rb
index 241fc98b673..62026ec7f0f 100644
--- a/lib/json_api_kit/request/individual.rb
+++ b/lib/json_api_kit/request/individual.rb
@@ -3,10 +3,6 @@
module JsonApiKit
class Request
class Individual < Request
- def scope(from:) = from.where(from.primary_key => id)
-
- private
-
def id = params[:id]
end
end
diff --git a/lib/json_api_kit/resource.rb b/lib/json_api_kit/resource.rb
index 163f30ef200..0836ee0df90 100644
--- a/lib/json_api_kit/resource.rb
+++ b/lib/json_api_kit/resource.rb
@@ -4,6 +4,7 @@ module JsonApiKit
class Resource
UnreadableAttribute = Class.new(StandardError)
+ include Adapting
include Naming
include Sorting
include Filtering
diff --git a/lib/json_api_kit/resource/adapting.rb b/lib/json_api_kit/resource/adapting.rb
new file mode 100644
index 00000000000..fb875ee4b12
--- /dev/null
+++ b/lib/json_api_kit/resource/adapting.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Resource
+ module Adapting
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :declared_adapter, default: Adapters::ActiveRecord, instance_accessor: false
+ private_class_method :declared_adapter, :declared_adapter=
+ end
+
+ class_methods do
+ def adapter(declaration = nil)
+ return declared_adapter unless declaration
+ self.declared_adapter =
+ case declaration
+ when Class
+ declaration
+ else
+ Adapters.const_get(declaration.to_s.camelize, false)
+ end
+ end
+ end
+
+ def adapter = @adapter ||= self.class.adapter.new(self)
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/anchoring.rb b/lib/json_api_kit/resource/anchoring.rb
index 83a31da244d..b035ff8f6c9 100644
--- a/lib/json_api_kit/resource/anchoring.rb
+++ b/lib/json_api_kit/resource/anchoring.rb
@@ -15,7 +15,7 @@ module JsonApiKit
class_methods do
def anchor(name, &condition)
- self.declared_anchors = declared_anchors + [Declarations::Anchor.for(name, &condition)]
+ self.declared_anchors = declared_anchors + [adapter.anchor(name, &condition)]
end
def anchor_names = declared_anchors.map(&:name)
@@ -25,21 +25,20 @@ module JsonApiKit
end
def anchored_by?(anchor_name:, ordering:)
- declared_anchor(anchor_name).then { it.nil? || it.locatable_in?(order(ordering)) }
+ adapter.anchored_by?(self, anchor_name:, ordering:)
end
- def anchors(guardian) = Declarations::Anchors.new(declared_anchors, guardian:)
+ def anchors(guardian) = new(guardian:).anchors(guardian)
+
+ def anchor_declarations = declared_anchors
private
def declared_anchor(name) = declared_anchors.detect { it.name == name.to_s }
end
- delegate :anchor_names, :anchor_accepts?, :anchors, to: :class
-
- def anchored_by?(anchor_name:, ordering:)
- anchors(guardian).fetch(anchor_name.to_s) { return true }.locatable_in?(order(ordering))
- end
+ delegate :anchor_names, :anchor_accepts?, :anchor_declarations, to: :class
+ delegate :anchors, :anchored_by?, :leading_sort_name, to: :adapter
end
end
end
diff --git a/lib/json_api_kit/resource/fields.rb b/lib/json_api_kit/resource/fields.rb
index 29da5514908..b6f8b7299a6 100644
--- a/lib/json_api_kit/resource/fields.rb
+++ b/lib/json_api_kit/resource/fields.rb
@@ -43,7 +43,6 @@ module JsonApiKit
guardian:,
attributes: declared_attributes,
relationships: declared_relationships,
- schema:,
type:,
)
end
diff --git a/lib/json_api_kit/resource/filtering.rb b/lib/json_api_kit/resource/filtering.rb
index 231c9cb3ee2..80a14d6133a 100644
--- a/lib/json_api_kit/resource/filtering.rb
+++ b/lib/json_api_kit/resource/filtering.rb
@@ -25,7 +25,7 @@ module JsonApiKit
delegate :names, to: :filters, prefix: :filter
- def apply_filters(rows, filtering = {}) = filters.apply(rows, filtering)
+ def apply_filters(rows, filtering = {}) = filters.apply(rows, filtering, adapter:)
def filters = @filters ||= self.class.filters.with(edition.removed_filters.for(type))
end
diff --git a/lib/json_api_kit/resource/naming.rb b/lib/json_api_kit/resource/naming.rb
index b5b1876b37d..45ab7c577f7 100644
--- a/lib/json_api_kit/resource/naming.rb
+++ b/lib/json_api_kit/resource/naming.rb
@@ -31,7 +31,7 @@ module JsonApiKit
self.declared_model = declaration
end
- def schema = Schema.new(model)
+ def schema = adapter.schema(self)
def type(declaration = nil)
return declared_type || inferred_type unless declaration
@@ -58,15 +58,17 @@ module JsonApiKit
end
def no_model(model)
- "#{self}: no model is named #{model.to_s.camelize}, declare it with `model SomeModel`"
+ "Cannot resolve model #{model.to_s.camelize} for #{self}. Declare `model SomeModel`."
end
def nothing_to_infer_from
- "#{inspect} is not named after what it exposes: declare `model SomeModel` and `type :things`"
+ "Cannot infer a model or resource type from #{inspect}. " \
+ "Declare `model SomeModel` and `type :things`."
end
end
- delegate :model, :schema, :type, :namespace, to: :class
+ delegate :model, :type, :namespace, to: :class
+ delegate :schema, to: :adapter
end
end
end
diff --git a/lib/json_api_kit/resource/paging.rb b/lib/json_api_kit/resource/paging.rb
index 21d092bc746..3c089926835 100644
--- a/lib/json_api_kit/resource/paging.rb
+++ b/lib/json_api_kit/resource/paging.rb
@@ -25,12 +25,11 @@ module JsonApiKit
def max_page_size = page_limits.max
- def paged_from?(cursor, ordering:) = order(ordering).compatible_with?(cursor:)
+ def paged_from?(cursor, ordering:) = adapter.paged_from?(self, cursor, ordering:)
end
delegate :page_limits, :page_size, :max_page_size, to: :class
-
- def paged_from?(cursor, ordering:) = order(ordering).compatible_with?(cursor:)
+ delegate :parse_cursor, :valid_cursor?, :paged_from?, to: :adapter
end
end
end
diff --git a/lib/json_api_kit/resource/query_interface.rb b/lib/json_api_kit/resource/query_interface.rb
index 26b40a9992b..5b0ac22fd69 100644
--- a/lib/json_api_kit/resource/query_interface.rb
+++ b/lib/json_api_kit/resource/query_interface.rb
@@ -15,9 +15,10 @@ module JsonApiKit
self.declared_scope = block
end
+ def scope_definition = declared_scope
+
def scope_for(guardian)
- return model.all unless declared_scope
- declared_scope.call(guardian)
+ new(guardian:).scope_for(guardian)
end
def all(params = {}, guardian:, scoped_to: nil, edition: Edition.current)
@@ -29,14 +30,14 @@ module JsonApiKit
end
end
- delegate :scope_for, to: :class
+ delegate :scope_definition, to: :class
+ delegate :scope_for, :record_for, :related_scope, :related_records, to: :adapter
delegate :default_sorts, to: :edition, private: true
def current_values(id) = CurrentValues.new(self, id:)
def all(params = {}, scoped_to: nil)
- Query::Collection.new(
- self,
+ adapter.all(
Request::Collection.new(
Request::Input.with_defaults(params, resource: self, default_sorts:),
guardian:,
@@ -47,8 +48,7 @@ module JsonApiKit
end
def find(id, params = {})
- Query::Individual.new(
- self,
+ adapter.find(
Request::Individual.new(
Request::Input.with_defaults(params, resource: self, default_sorts:).merge(id:),
guardian:,
@@ -56,14 +56,6 @@ module JsonApiKit
),
)
end
-
- def related_scope(name, owner_id:)
- schema.association(name.to_sym, [record_for(owner_id)]).related_scope
- end
-
- def record_for(id)
- scope_for(guardian).find_by(schema.primary_key => id) or raise NotFound
- end
end
end
end
diff --git a/lib/json_api_kit/resource/sorting.rb b/lib/json_api_kit/resource/sorting.rb
index 5a3c28cfbf2..5c6d12dbd15 100644
--- a/lib/json_api_kit/resource/sorting.rb
+++ b/lib/json_api_kit/resource/sorting.rb
@@ -28,8 +28,10 @@ module JsonApiKit
class_methods do
include Ordering
+ def order(ordering) = adapter.order(self, ordering)
+
def sort(name, **options)
- self.declared_sorts = declared_sorts + [Declarations::Sort.for(name, **options)]
+ self.declared_sorts = declared_sorts + [Declarations::Sort.new(name, **options)]
end
def default_sort(ordering)
@@ -40,10 +42,12 @@ module JsonApiKit
self.declared_unique_by = columns
end
+ def unique_key = declared_unique_by
+
def sort_names = declared_sorts.map(&:name)
def sorts
- Declarations::Sorts.new(declared_sorts, schema:, unique_by: declared_unique_by)
+ Declarations::Sorts.new(declared_sorts)
end
private
@@ -53,6 +57,7 @@ module JsonApiKit
include Ordering
+ delegate :unique_key, to: :class
delegate :names, to: :sorts, prefix: :sort
def sorts = @sorts ||= self.class.sorts.with(edition.removed_sorts.for(type))
diff --git a/lib/json_api_kit/resource/sorting/ordering.rb b/lib/json_api_kit/resource/sorting/ordering.rb
index e2507208e1f..428d54c9408 100644
--- a/lib/json_api_kit/resource/sorting/ordering.rb
+++ b/lib/json_api_kit/resource/sorting/ordering.rb
@@ -6,11 +6,11 @@ module JsonApiKit
module Ordering
def default_ordering(ordering = current_default_ordering)
verify_sorts(ordering.keys)
- ordering.each_value { Pagination::Direction.for(it) }
+ ordering.each_value { Declarations::Sort.verify_direction!(it) }
ordering.transform_keys(&:to_s).freeze
end
- def order(ordering) = Pagination::Order.new(sorts.keyset(ordering), type:)
+ def order(ordering) = adapter.order(ordering)
def sortable_by?(ordering:) = (ordering.keys - sort_names).empty?
@@ -22,8 +22,8 @@ module JsonApiKit
end
def no_such_sort(names)
- "#{self}: there is no sort named #{names.join(", ")}, " \
- "declare it with `sort` before naming it as the default"
+ "#{self}: default sort uses undeclared sorts: #{names.join(", ")}. " \
+ "Add the missing `sort` declarations."
end
end
end
diff --git a/lib/json_api_kit/schema.rb b/lib/json_api_kit/schema.rb
deleted file mode 100644
index 4a3fa28795c..00000000000
--- a/lib/json_api_kit/schema.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-# 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
deleted file mode 100644
index 2930fa6f14b..00000000000
--- a/lib/json_api_kit/scoping.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-# 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
index 412dfd62cf7..97d57472d8d 100644
--- a/lib/json_api_kit/sideload.rb
+++ b/lib/json_api_kit/sideload.rb
@@ -4,41 +4,34 @@ module JsonApiKit
class Sideload
delegate :name, to: :relationship
- def initialize(relationship, paths:, rows:, request:, schema:)
+ def initialize(relationship, paths:, rows:, request:, owner_resource:)
@relationship = relationship
@paths = paths
@rows = rows
@request = request
- @schema = schema
+ @owner_resource = owner_resource
end
def linkage_for(row) = relationship.linkage(related_to(row))
private
- attr_reader :relationship, :paths, :rows, :request, :schema
+ attr_reader :relationship, :paths, :rows, :request, :owner_resource
- def records = related_listing.records
-
- def related_listing
- @related_listing ||=
- relationship.listing(
- request.for_sideload(paths),
- guardian: request.guardian,
- edition: request.edition,
- scoped_to: relationship.scoping(association),
- )
- end
-
- def related_to(row) = related_by_row.fetch(row.record, Records.new([]))
+ 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) }
+ @related_by_row ||= related_records.records_by_owner(request.for_sideload(paths))
end
def owner_records = rows.map(&:record)
- def association = @association ||= schema.association(name.to_sym, owner_records)
+ def related_records
+ resource.related_records(relationship, owners: owner_records, owner_resource:)
+ end
+
+ def resource
+ @resource ||= relationship.resource.new(guardian: request.guardian, edition: request.edition)
+ end
end
end
diff --git a/lib/json_api_kit/sideloads.rb b/lib/json_api_kit/sideloads.rb
index 112fbdeece6..5d6e115cf89 100644
--- a/lib/json_api_kit/sideloads.rb
+++ b/lib/json_api_kit/sideloads.rb
@@ -2,7 +2,7 @@
module JsonApiKit
class Sideloads
- def self.for(relationships, paths:, rows:, request:, schema:)
+ def self.for(relationships, paths:, rows:, request:, resource:)
new(
relationships.map do |relationship|
Sideload.new(
@@ -10,7 +10,7 @@ module JsonApiKit
paths: paths.next_for(relationship.name),
rows:,
request:,
- schema:,
+ owner_resource: resource,
)
end,
)
diff --git a/lib/json_api_kit/version_change/removed_sort.rb b/lib/json_api_kit/version_change/removed_sort.rb
index a00961f7e6f..70c4e688c30 100644
--- a/lib/json_api_kit/version_change/removed_sort.rb
+++ b/lib/json_api_kit/version_change/removed_sort.rb
@@ -10,7 +10,7 @@ module JsonApiKit
def initialize(type, name, **options)
@type = type.to_s
@name = "__removed_sort_#{object_id}"
- @sort = JsonApiKit::Declarations::Sort.for(name, **options)
+ @sort = JsonApiKit::Declarations::Sort.new(name, **options)
end
def transformations
diff --git a/spec/integration/json_api_kit/adapters_spec.rb b/spec/integration/json_api_kit/adapters_spec.rb
new file mode 100644
index 00000000000..cd8f8c0090b
--- /dev/null
+++ b/spec/integration/json_api_kit/adapters_spec.rb
@@ -0,0 +1,202 @@
+# frozen_string_literal: true
+
+module JsonApiKitAdapterSpec
+ class ContextAdapter < JsonApiKit::Adapters::ActiveRecord
+ def initialize(resource)
+ super
+ @owner_id = resource.guardian.user.id
+ end
+
+ def scope_for(guardian) = super.where(user_id: @owner_id)
+ end
+
+ class ContextTopicResource < JsonApiKit::Resource
+ adapter ContextAdapter
+ model Topic
+ type :topics
+
+ attribute :title
+ sort :title
+ anchor :title
+ anchor(:mine) { |topics, guardian| topics.where(user_id: guardian.user.id) }
+ end
+
+ class AlphabeticalAdapter < ContextAdapter
+ class Definition < JsonApiKit::Adapters::ActiveRecord::Definition
+ def order(ordering) = super(ordering.presence || { "title" => :asc })
+ end
+ end
+end
+
+RSpec.describe "JSON:API ActiveRecord adapter integration" do
+ let(:guardian) { Guardian.new }
+ let(:edition) { JsonApiKit::Edition.current }
+ let(:params) { {} }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")
+ end
+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }
+
+ describe "an explicit ActiveRecord adapter" do
+ subject(:document) { JsonApiKit::Document::Individual.for(id, params, resource:, client:) }
+
+ fab!(:topic)
+
+ let(:id) { topic.id.to_s }
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ adapter :active_record
+ model Topic
+ type :topics
+ attribute :title
+ end
+ end
+
+ it "renders the database record" do
+ expect(document.to_h.fetch(:data)).to include(id:, attributes: { "title" => topic.title })
+ end
+ end
+
+ describe "inherited ActiveRecord declarations" do
+ subject(:ids) do
+ JsonApiKit::Document::Collection
+ .for({}, resource:, client:)
+ .to_h
+ .fetch(:data)
+ .map { it.fetch(:id) }
+ end
+
+ fab!(:first_topic) { Fabricate(:topic, title: "Zulu adapter topic") }
+ fab!(:second_topic) { Fabricate(:topic, title: "Alpha adapter topic") }
+
+ let(:parent_resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ unique_by :title, :id
+ end
+ end
+
+ context "when a subclass clears the inherited scope" do
+ let(:parent_resource) { Class.new(super()) { scope { Topic.none } } }
+ let(:resource) { Class.new(parent_resource) { scope } }
+
+ it "reads the records through the default scope" do
+ expect(ids).to contain_exactly(first_topic.id.to_s, second_topic.id.to_s)
+ end
+ end
+
+ context "when a subclass clears the inherited unique key" do
+ let(:resource) { Class.new(parent_resource) { unique_by } }
+
+ it "orders records by the model's primary key" do
+ expect(ids).to eq([first_topic.id.to_s, second_topic.id.to_s])
+ end
+ end
+ end
+
+ describe "an adapter that uses request context" do
+ fab!(:author, :user)
+ fab!(:oldest) do
+ Fabricate(:topic, user: author, title: "Zulu context topic", created_at: Time.utc(2026, 8, 1))
+ end
+ fab!(:newest) do
+ Fabricate(
+ :topic,
+ user: author,
+ title: "Alpha context topic",
+ created_at: Time.utc(2026, 8, 2),
+ )
+ end
+ fab!(:other_topic, :topic)
+
+ let(:guardian) { author.guardian }
+ let(:resource) { JsonApiKitAdapterSpec::ContextTopicResource }
+ let(:records) { resource.all(guardian:).records.map(&:record) }
+ let(:ordering) { { "title" => :asc } }
+ let(:cursor) { resource.order(ordering).locate(Topic.where(id: oldest.id)).cursor }
+ let(:anchoring) { JsonApiKit::Anchoring.for(:mine) }
+ let(:anchored_topic) do
+ resource
+ .anchors(guardian)
+ .locate(anchoring, scope: Topic.all, order: resource.order({}))
+ .record
+ end
+
+ it "reads the class schema without request context" do
+ expect(resource.schema.primary_key).to eq(:id)
+ end
+
+ it "builds the class ordering without request context" do
+ expect(resource.order(ordering).leading.name).to eq(:title)
+ end
+
+ it "checks the class cursor against its ordering" do
+ expect(resource).to be_paged_from(cursor, ordering:)
+ end
+
+ it "checks the class anchor against its ordering" do
+ expect(resource).to be_anchored_by(anchor_name: :title, ordering:)
+ end
+
+ it "supplies the guardian to the class scope lookup" do
+ expect(resource.scope_for(guardian)).to contain_exactly(oldest, newest)
+ end
+
+ it "supplies the guardian to computed anchors" do
+ expect(anchored_topic).to eq(oldest)
+ end
+
+ it "uses the same context for a collection lookup" do
+ expect(records).to contain_exactly(oldest, newest)
+ end
+
+ context "when the adapter specializes its definition" do
+ let(:resource) { Class.new(super()) { adapter JsonApiKitAdapterSpec::AlphabeticalAdapter } }
+
+ it "uses the specialization for class operations" do
+ expect(resource.order({}).leading.name).to eq(:title)
+ end
+
+ it "uses the specialization for request operations" do
+ expect(records).to eq([newest, oldest])
+ end
+ end
+
+ context "when the requested version retains a removed sort" do
+ let(:edition) do
+ JsonApiKit::Edition.new(
+ [
+ Class
+ .new(JsonApiKit::VersionChange) { resource(:topics) { removed_sort :created_at } }
+ .new(__FILE__),
+ ],
+ )
+ end
+ let(:params) { { sort: "createdAt" } }
+ let(:document) { JsonApiKit::Document::Collection.for(params, resource:, client:) }
+ let(:ids) { document.to_h.fetch(:data).map { it.fetch(:id) } }
+
+ before { resource.order(ordering) }
+
+ it "uses the instance's effective declarations" do
+ expect(ids).to eq([oldest.id.to_s, newest.id.to_s])
+ end
+
+ context "when a current request follows the historical request" do
+ let(:current_client) do
+ JsonApiKit::Client.new(guardian:, edition: JsonApiKit::Edition.current, urls: client.urls)
+ end
+ let(:current_document) do
+ JsonApiKit::Document::Collection.for(params, resource:, client: current_client)
+ end
+
+ before { document.to_h }
+
+ it "keeps the current edition's declarations independent" do
+ expect(current_document.status).to eq("400")
+ end
+ end
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/anchors_spec.rb b/spec/integration/json_api_kit/anchors_spec.rb
index 16d903f9d2c..29532731b5f 100644
--- a/spec/integration/json_api_kit/anchors_spec.rb
+++ b/spec/integration/json_api_kit/anchors_spec.rb
@@ -277,8 +277,8 @@ RSpec.describe "a listing entered at an anchor" do
expect(document).to eq(
errors: [
refusal(
- title: "No row for the anchor",
- detail: "No record has id -1.",
+ title: "No record matches the anchor",
+ detail: "No record matches anchor id=-1.",
parameter: "page[anchor][id]",
),
],
diff --git a/spec/integration/json_api_kit/custom_adapters_spec.rb b/spec/integration/json_api_kit/custom_adapters_spec.rb
new file mode 100644
index 00000000000..8b5e068930b
--- /dev/null
+++ b/spec/integration/json_api_kit/custom_adapters_spec.rb
@@ -0,0 +1,156 @@
+# frozen_string_literal: true
+
+module JsonApiKitAdapterSpec
+ class Note < Data.define(:id, :owner_id, :text)
+ def self.records = []
+ end
+
+ class TestAdapter < JsonApiKit::Adapter
+ def all(request, scoped_to: nil)
+ JsonApiKit::Query::Result.new(
+ resource,
+ request,
+ records: resource.apply_filters(scoped_to || Note.records, request.filtering),
+ )
+ end
+
+ def filter(records, name, value) = records.select { it.public_send(name) == value }
+
+ def related_records(_relationship, owners:, owner_resource:)
+ RelatedNotes.new(resource, owners)
+ end
+ end
+
+ class RelatedNotes
+ def initialize(resource, owners)
+ @resource = resource
+ @owners = owners
+ end
+
+ def scope = Note.records.select { owners.map(&:id).include?(it.owner_id) }
+
+ def records_by_owner(params)
+ owners.to_h do |owner|
+ [owner, JsonApiKit::Records.new(records(params).select { it.record.owner_id == owner.id })]
+ end
+ end
+
+ private
+
+ attr_reader :resource, :owners
+
+ def records(params) = @records ||= resource.all(params, scoped_to: scope).records
+ end
+
+ class NoteResource < JsonApiKit::Resource
+ adapter TestAdapter
+ model Note
+ type :notes
+
+ attribute :text
+ filter :text
+ end
+
+ class TopicResource < JsonApiKit::Resource
+ model Topic
+ type :topics
+
+ attribute :title
+ has_many :notes, resource: NoteResource
+ end
+end
+
+RSpec.describe "JSON:API with a test adapter for plain Ruby objects" do
+ let(:guardian) { Guardian.new }
+ let(:edition) { JsonApiKit::Edition.current }
+ let(:resource) { JsonApiKitAdapterSpec::NoteResource }
+ let(:params) { {} }
+ let(:notes) do
+ [
+ JsonApiKitAdapterSpec::Note.new(id: "first", owner_id: 1, text: "First note"),
+ JsonApiKitAdapterSpec::Note.new(id: "second", owner_id: 2, text: "Second note"),
+ ]
+ end
+ let(:client) do
+ JsonApiKit::Client.new(
+ guardian:,
+ edition:,
+ urls:
+ JsonApiKit::Urls.new(
+ base: "https://example.com/api",
+ current: "https://example.com/api/#{resource.type}",
+ ),
+ )
+ end
+
+ before { allow(JsonApiKitAdapterSpec::Note).to receive(:records).and_return(notes) }
+
+ describe "a collection" do
+ subject(:document) { JsonApiKit::Document::Collection.for(params, resource:, client:).to_h }
+
+ let(:ids) { document.fetch(:data).map { it.fetch(:id) } }
+
+ context "when the request supplies a sparse fieldset" do
+ let(:params) { { fields: { notes: "" } } }
+
+ it "renders identifiers without attributes", :aggregate_failures do
+ expect(ids).to contain_exactly("first", "second")
+ expect(document.fetch(:data)).to all(exclude(:attributes))
+ end
+ end
+
+ context "when a historical request filters and selects a renamed field" do
+ let(:edition) do
+ JsonApiKit::Edition.new(
+ [
+ Class
+ .new(JsonApiKit::VersionChange) do
+ resource :notes do
+ renamed_attribute from: :body, to: :text
+ renamed_filter from: :body, to: :text
+ end
+ end
+ .new(__FILE__),
+ ],
+ )
+ end
+ let(:params) { { fields: { notes: "body" }, filter: { body: "Second note" } } }
+
+ it "renders the requested version of the field" do
+ expect(document.fetch(:data)).to contain_exactly(
+ a_hash_including(id: "second", attributes: { "body" => "Second note" }),
+ )
+ end
+ end
+
+ context "when the resource inherits its adapter" do
+ let(:resource) { Class.new(super()) }
+
+ it "uses the inherited adapter" do
+ expect(ids).to contain_exactly("first", "second")
+ end
+ end
+ end
+
+ describe "a relationship between adapters" do
+ subject(:document) do
+ JsonApiKit::Document::Individual.for(topic.id, { include: "notes" }, resource:, client:).to_h
+ end
+
+ fab!(:topic)
+
+ let(:resource) { JsonApiKitAdapterSpec::TopicResource }
+ let(:notes) do
+ [JsonApiKitAdapterSpec::Note.new(id: "first", owner_id: topic.id, text: "A note")]
+ end
+
+ it "includes records without an ActiveRecord association", :aggregate_failures do
+ expect(document.dig(:data, :relationships, "notes", :data)).to eq(
+ [{ type: "notes", id: "first" }],
+ )
+ expect(document.fetch(:included)).to contain_exactly(
+ a_hash_including(type: "notes", id: "first", attributes: { "text" => "A note" }),
+ )
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/errors_spec.rb b/spec/integration/json_api_kit/errors_spec.rb
index de68d9c04bd..35b54d207bd 100644
--- a/spec/integration/json_api_kit/errors_spec.rb
+++ b/spec/integration/json_api_kit/errors_spec.rb
@@ -653,8 +653,8 @@ RSpec.describe "a refused request" do
expect(document).to eq(
errors: [
refusal(
- title: "No row for the anchor",
- detail: "No record has id \"not a number\".",
+ title: "No record matches the anchor",
+ detail: "No record matches anchor id=\"not a number\".",
parameter: "page[anchor][id]",
),
],
@@ -669,8 +669,8 @@ RSpec.describe "a refused request" do
expect(document).to eq(
errors: [
refusal(
- title: "No row for the anchor",
- detail: "No record has id -1.",
+ title: "No record matches the anchor",
+ detail: "No record matches anchor id=-1.",
parameter: "page[anchor][id]",
),
],
@@ -734,7 +734,7 @@ RSpec.describe "a refused request" do
it "raises a split order error" do
expect { document }.to raise_error(
- JsonApiKit::Pagination::PagePerOwner::SplitOrder,
+ JsonApiKit::Adapters::ActiveRecord::Pagination::PagePerOwner::SplitOrder,
/edited_at/,
)
end
diff --git a/spec/lib/json_api_kit/association/through_spec.rb b/spec/lib/json_api_kit/adapters/active_record/association/through_spec.rb
similarity index 88%
rename from spec/lib/json_api_kit/association/through_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/association/through_spec.rb
index 55b6225115f..1c3fe7d0ba1 100644
--- a/spec/lib/json_api_kit/association/through_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/association/through_spec.rb
@@ -1,7 +1,9 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Association::Through do
- subject(:association) { JsonApiKit::Schema.new(Topic).association(:tags, owner_rows) }
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Association::Through do
+ subject(:association) do
+ JsonApiKit::Adapters::ActiveRecord::Schema.new(Topic).association(:tags, owner_rows)
+ end
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") }
diff --git a/spec/lib/json_api_kit/association_spec.rb b/spec/lib/json_api_kit/adapters/active_record/association_spec.rb
similarity index 94%
rename from spec/lib/json_api_kit/association_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/association_spec.rb
index a00d69a7223..e880f6a41c7 100644
--- a/spec/lib/json_api_kit/association_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/association_spec.rb
@@ -1,7 +1,9 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Association do
- subject(:association) { JsonApiKit::Schema.new(Topic).association(name, owner_rows) }
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Association do
+ subject(:association) do
+ JsonApiKit::Adapters::ActiveRecord::Schema.new(Topic).association(name, owner_rows)
+ end
fab!(:author, :user)
fab!(:topic) { Fabricate(:topic, user: author, title: "A topic that relates to rows") }
diff --git a/spec/lib/json_api_kit/columns_spec.rb b/spec/lib/json_api_kit/adapters/active_record/columns_spec.rb
similarity index 96%
rename from spec/lib/json_api_kit/columns_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/columns_spec.rb
index 7a5228984a3..0ce8a1f1ad1 100644
--- a/spec/lib/json_api_kit/columns_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/columns_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Columns do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Columns do
subject(:columns) { described_class.for(%i[id title]) }
fab!(:topic) { Fabricate(:topic, title: "A row read column by column") }
diff --git a/spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute_spec.rb
similarity index 95%
rename from spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute_spec.rb
index 6ea1461e626..27ef25b2555 100644
--- a/spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/attribute_spec.rb
@@ -2,7 +2,7 @@
RSpec::Matchers.alias_matcher :accept, :be_accepts
-RSpec.describe JsonApiKit::Declarations::Anchor::Attribute do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor::Attribute do
subject(:anchor) { described_class.new(:created_at) }
fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
diff --git a/spec/lib/json_api_kit/declarations/anchor/computed_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/computed_spec.rb
similarity index 93%
rename from spec/lib/json_api_kit/declarations/anchor/computed_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/anchor/computed_spec.rb
index 19319d93d1f..54366d8fcbb 100644
--- a/spec/lib/json_api_kit/declarations/anchor/computed_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/computed_spec.rb
@@ -2,7 +2,7 @@
RSpec::Matchers.alias_matcher :accept, :be_accepts
-RSpec.describe JsonApiKit::Declarations::Anchor::Computed do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor::Computed do
subject(:anchor) do
described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
end
diff --git a/spec/lib/json_api_kit/declarations/anchor/identity_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/identity_spec.rb
similarity index 85%
rename from spec/lib/json_api_kit/declarations/anchor/identity_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/anchor/identity_spec.rb
index 855e99aa5e9..1a6850b4be1 100644
--- a/spec/lib/json_api_kit/declarations/anchor/identity_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor/identity_spec.rb
@@ -2,7 +2,7 @@
RSpec::Matchers.alias_matcher :accept, :be_accepts
-RSpec.describe JsonApiKit::Declarations::Anchor::Identity do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor::Identity do
subject(:anchor) { described_class.new(:id) }
fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
@@ -41,7 +41,9 @@ RSpec.describe JsonApiKit::Declarations::Anchor::Identity do
let(:anchoring) { JsonApiKit::Anchoring.for(id: -1) }
it "raises no row for the anchor" do
- expect { located_row }.to raise_error(JsonApiKit::Declarations::Anchor::NoRow)
+ expect { located_row }.to raise_error(
+ JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor::NoRow,
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/declarations/anchor_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor_spec.rb
similarity index 89%
rename from spec/lib/json_api_kit/declarations/anchor_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/anchor_spec.rb
index bb3ee5e6553..e7611046f50 100644
--- a/spec/lib/json_api_kit/declarations/anchor_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/anchor_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Declarations::Anchor do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor do
describe ".for" do
subject(:anchor) { described_class.for(:created_at) }
@@ -34,7 +34,7 @@ RSpec.describe JsonApiKit::Declarations::Anchor do
describe "#title" do
it "returns the title of the error" do
- expect(error.title).to eq("No row for the anchor")
+ expect(error.title).to eq("No record matches the anchor")
end
end
diff --git a/spec/lib/json_api_kit/declarations/anchors_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/anchors_spec.rb
similarity index 86%
rename from spec/lib/json_api_kit/declarations/anchors_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/anchors_spec.rb
index a00adb0981c..0dbdf3ef90f 100644
--- a/spec/lib/json_api_kit/declarations/anchors_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/anchors_spec.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Declarations::Anchors do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Anchors do
subject(:anchors) { described_class.new(declarations, guardian:) }
- let(:anchor_class) { JsonApiKit::Declarations::Anchor }
+ let(:anchor_class) { JsonApiKit::Adapters::ActiveRecord::Declarations::Anchor }
let(:created_at_anchor) { anchor_class.for(:created_at) }
let(:declarations) { [anchor_class.for(:id), created_at_anchor] }
let(:guardian) { Guardian.new }
@@ -38,7 +38,7 @@ RSpec.describe JsonApiKit::Declarations::Anchors do
let(:scope) { Topic.all }
let(:anchoring) { JsonApiKit::Anchoring.for(created_at: Time.utc(2026, 8, 3)) }
- let(:row) { instance_double(JsonApiKit::Pagination::Row) }
+ let(:row) { instance_double(JsonApiKit::Adapters::ActiveRecord::Pagination::Row) }
before { allow(created_at_anchor).to receive(:locate).and_return(row) }
diff --git a/spec/lib/json_api_kit/declarations/sort_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/sort_spec.rb
similarity index 76%
rename from spec/lib/json_api_kit/declarations/sort_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/declarations/sort_spec.rb
index 2f36399f5de..911f6fc44c1 100644
--- a/spec/lib/json_api_kit/declarations/sort_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/sort_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Declarations::Sort do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Sort do
subject(:sort) { described_class.for(:created_at) }
describe "#name" do
@@ -10,7 +10,9 @@ RSpec.describe JsonApiKit::Declarations::Sort do
end
describe "#key" do
- subject(:key) { sort.key(schema: JsonApiKit::Schema.new(Topic), direction: :desc) }
+ subject(:key) do
+ sort.key(schema: JsonApiKit::Adapters::ActiveRecord::Schema.new(Topic), direction: :desc)
+ end
it "orders by the column of the same name" do
expect(key.name).to eq(:created_at)
@@ -61,7 +63,9 @@ RSpec.describe JsonApiKit::Declarations::Sort do
it "carries those joins" do
expect(key.joins).to eq(
- JsonApiKit::Joins.for("LEFT JOIN users ON users.id = topics.user_id"),
+ JsonApiKit::Adapters::ActiveRecord::Joins.for(
+ "LEFT JOIN users ON users.id = topics.user_id",
+ ),
)
end
@@ -76,7 +80,7 @@ RSpec.describe JsonApiKit::Declarations::Sort do
end
it "joins the association" do
- expect(key.joins).to eq(JsonApiKit::Joins.for(:user))
+ expect(key.joins).to eq(JsonApiKit::Adapters::ActiveRecord::Joins.for(:user))
end
it "names the key with an underscore" do
@@ -86,7 +90,9 @@ RSpec.describe JsonApiKit::Declarations::Sort do
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) }
+ subject(:key) do
+ sort.key(schema: JsonApiKit::Adapters::ActiveRecord::Schema.new(Post), direction: :desc)
+ end
let(:sort) { described_class.for("topic.id") }
@@ -98,7 +104,7 @@ RSpec.describe JsonApiKit::Declarations::Sort do
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))
+ expect(key.joins).to eq(JsonApiKit::Adapters::ActiveRecord::Joins.for(:user))
end
end
@@ -113,7 +119,9 @@ RSpec.describe JsonApiKit::Declarations::Sort do
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"),
+ JsonApiKit::Adapters::ActiveRecord::Joins.for(
+ "LEFT JOIN users ON users.id = topics.user_id",
+ ),
)
end
end
@@ -127,7 +135,12 @@ RSpec.describe JsonApiKit::Declarations::Sort do
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/) }
+ it do
+ expect { key }.to raise_error(
+ JsonApiKit::Adapters::ActiveRecord::Schema::MissingAssociation,
+ /author/,
+ )
+ end
end
end
end
diff --git a/spec/lib/json_api_kit/adapters/active_record/declarations/sorts_spec.rb b/spec/lib/json_api_kit/adapters/active_record/declarations/sorts_spec.rb
new file mode 100644
index 00000000000..c4bfd37a28d
--- /dev/null
+++ b/spec/lib/json_api_kit/adapters/active_record/declarations/sorts_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Declarations::Sorts do
+ subject(:sorts) { described_class.new(collection, builder:, unique_by:) }
+
+ let(:builder) { resource.adapter }
+ let(:resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ .new(guardian: Guardian.new)
+ end
+ 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(:collection) { JsonApiKit::Declarations::Sorts.new(declarations) }
+ let(:unique_by) { [] }
+
+ describe "#keyset" do
+ subject(:keyset) { sorts.keyset(ordering) }
+
+ let(:ordering) { { "created_at" => :desc } }
+ let(:key_ordering) { keyset.keys.map { [it.name, it.direction.to_sym] } }
+
+ it "builds a stable descending order" do
+ expect(key_ordering).to eq([%i[created_at desc], %i[id 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(key_ordering).to eq([%i[last_posted_at asc], %i[created_at desc], %i[id asc]])
+ 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 the ordering is empty" do
+ let(:ordering) { {} }
+
+ it "orders by the unique key in ascending order" do
+ expect(key_ordering).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(key_ordering).to eq([%i[created_at desc], %i[title desc], %i[id desc]])
+ 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(key_ordering).to eq([%i[created_at desc], %i[title desc]])
+ 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(key_ordering).to eq([%i[created_at desc], %i[id asc]])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/joins_spec.rb b/spec/lib/json_api_kit/adapters/active_record/joins_spec.rb
similarity index 96%
rename from spec/lib/json_api_kit/joins_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/joins_spec.rb
index 1ed035db208..ff5fa567424 100644
--- a/spec/lib/json_api_kit/joins_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/joins_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Joins do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Joins do
subject(:joins) { described_class.for(declarations) }
fab!(:section) { Fabricate(:category, name: "A section of the forum") }
diff --git a/spec/lib/json_api_kit/adapters/active_record/page/requested_spec.rb b/spec/lib/json_api_kit/adapters/active_record/page/requested_spec.rb
new file mode 100644
index 00000000000..c9341cec80f
--- /dev/null
+++ b/spec/lib/json_api_kit/adapters/active_record/page/requested_spec.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Page::Requested do
+ describe ".from" do
+ subject(:requested_page) { described_class.from(request, adapter:) }
+
+ let(:request) { instance_double(JsonApiKit::Request::Collection, page: parameters, anchoring:) }
+ let(:parameters) do
+ { size: 2, after: nil, before: nil, include_anchor: nil, item_cursors: true }
+ end
+ let(:page_options) { { size: 2, after: nil, before: nil, anchoring: nil } }
+ let(:anchoring) { nil }
+ let(:adapter) { instance_double(JsonApiKit::Adapters::ActiveRecord) }
+ let(:cursor) { instance_double(JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor) }
+ let(:raw_cursor) { "backend-cursor" }
+
+ before do
+ allow(described_class).to receive(:for).and_call_original
+ allow(adapter).to receive(:parse_cursor).with(raw_cursor).and_return(cursor)
+ end
+
+ it "excludes representation options and omitted page values" do
+ requested_page
+
+ expect(described_class).to have_received(:for).with(**page_options)
+ end
+
+ context "when the page has an after cursor" do
+ let(:parameters) { super().merge(after: raw_cursor) }
+ let(:page_options) { super().merge(after: cursor) }
+
+ it "uses the adapter's parsed cursor" do
+ requested_page
+
+ expect(described_class).to have_received(:for).with(**page_options)
+ end
+ end
+
+ context "when the page has a before cursor" do
+ let(:parameters) { super().merge(before: raw_cursor) }
+ let(:page_options) { super().merge(before: cursor) }
+
+ it "uses the adapter's parsed cursor" do
+ requested_page
+
+ expect(described_class).to have_received(:for).with(**page_options)
+ end
+ end
+
+ context "when the page has an anchor" do
+ let(:anchoring) { JsonApiKit::Anchoring.for(id: 12) }
+ let(:parameters) do
+ super().merge(anchor: { id: 12 }, before_size: 1, after_size: 1, include_anchor: false)
+ end
+ let(:page_options) do
+ super().merge(anchoring:, before_size: 1, after_size: 1, include_anchor: false)
+ end
+
+ it "preserves the anchor and window options" do
+ requested_page
+
+ expect(described_class).to have_received(:for).with(**page_options)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/around_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/around_spec.rb
similarity index 90%
rename from spec/lib/json_api_kit/pagination/around_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/around_spec.rb
index 148453922c7..3b69f5268fe 100644
--- a/spec/lib/json_api_kit/pagination/around_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/around_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Around do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Around do
subject(:page) { described_class.new(scope, order:, row:, before:, after:, include_row:) }
fab!(:first_topic, :topic)
@@ -12,8 +12,10 @@ RSpec.describe JsonApiKit::Pagination::Around do
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:)]),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Order.new(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:)],
+ ),
)
end
let(:scope) { Topic.where(id: topics.map(&:id)) }
diff --git a/spec/lib/json_api_kit/pagination/cursor_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/cursor_spec.rb
similarity index 82%
rename from spec/lib/json_api_kit/pagination/cursor_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/cursor_spec.rb
index da252363a2f..f487c02df97 100644
--- a/spec/lib/json_api_kit/pagination/cursor_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/cursor_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Cursor do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor do
subject(:cursor) { described_class.new(values) }
let(:values) { [42, "alice"] }
@@ -68,11 +68,14 @@ RSpec.describe JsonApiKit::Pagination::Cursor do
end
end
- context "with a value no cursor can carry" do
+ context "when the value has an unsupported type" do
let(:value) { { id: 1 } }
it "refuses the value" do
- expect { cursor_value }.to raise_error(described_class::UnsupportedValue)
+ expect { cursor_value }.to raise_error(
+ described_class::UnsupportedValue,
+ "Unsupported cursor value type: Hash.",
+ )
end
end
@@ -86,7 +89,7 @@ RSpec.describe JsonApiKit::Pagination::Cursor do
end
describe ".valid?" do
- subject { described_class }
+ subject(:cursor_type) { described_class }
let(:wire_cursor) { cursor.to_s }
@@ -116,19 +119,25 @@ RSpec.describe JsonApiKit::Pagination::Cursor do
end
end
- context "when the string holds no list of values" do
+ context "when the decoded JSON is not an array" do
let(:wire_cursor) { Base64.urlsafe_encode64(%({"id":1}), padding: false) }
it "refuses the string" do
- expect { parsed_cursor }.to raise_error(ArgumentError)
+ expect { parsed_cursor }.to raise_error(
+ ArgumentError,
+ "Decoded cursor must be a JSON array.",
+ )
end
end
- context "when the list holds another list" do
+ context "when the decoded array contains another array" do
let(:wire_cursor) { Base64.urlsafe_encode64("[[1]]", padding: false) }
it "refuses the string" do
- expect { parsed_cursor }.to raise_error(ArgumentError)
+ expect { parsed_cursor }.to raise_error(
+ described_class::UnsupportedValue,
+ "Unsupported cursor value type: Array.",
+ )
end
end
@@ -136,7 +145,10 @@ RSpec.describe JsonApiKit::Pagination::Cursor do
let(:wire_cursor) { "" }
it "refuses the string" do
- expect { parsed_cursor }.to raise_error(ArgumentError)
+ expect { parsed_cursor }.to raise_error(
+ ArgumentError,
+ "Decoded cursor contains invalid JSON.",
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/pagination/direction_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/direction_spec.rb
similarity index 97%
rename from spec/lib/json_api_kit/pagination/direction_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/direction_spec.rb
index 8b52a35c19f..68ecce01b32 100644
--- a/spec/lib/json_api_kit/pagination/direction_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/direction_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Direction do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Direction do
subject(:direction) { described_class.for(declaration) }
let(:declaration) { :asc }
diff --git a/spec/lib/json_api_kit/pagination/keyset/key_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/keyset/key_spec.rb
similarity index 98%
rename from spec/lib/json_api_kit/pagination/keyset/key_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/keyset/key_spec.rb
index effb6e39842..7819a586e6a 100644
--- a/spec/lib/json_api_kit/pagination/keyset/key_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/keyset/key_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Keyset::Key do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key do
subject(:key) { described_class.new(:created_at, model:) }
let(:model) { Topic }
@@ -97,7 +97,7 @@ RSpec.describe JsonApiKit::Pagination::Keyset::Key do
end
it "keeps the joins its SQL needs" do
- expect(reversed_key.joins).to eq(JsonApiKit::Joins.for(:user))
+ expect(reversed_key.joins).to eq(JsonApiKit::Adapters::ActiveRecord::Joins.for(:user))
end
context "when the key is nullable" do
diff --git a/spec/lib/json_api_kit/pagination/keyset_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/keyset_spec.rb
similarity index 97%
rename from spec/lib/json_api_kit/pagination/keyset_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/keyset_spec.rb
index e5b1beebefb..23d2659bb9c 100644
--- a/spec/lib/json_api_kit/pagination/keyset_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/keyset_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Keyset do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset do
subject(:keyset) { described_class.new(keys) }
let(:model) { Topic }
@@ -149,7 +149,7 @@ RSpec.describe JsonApiKit::Pagination::Keyset do
end
it "returns each join once" do
- expect(joins).to eq(JsonApiKit::Joins.for(:user))
+ expect(joins).to eq(JsonApiKit::Adapters::ActiveRecord::Joins.for(:user))
end
end
diff --git a/spec/lib/json_api_kit/pagination/nulls_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/nulls_spec.rb
similarity index 92%
rename from spec/lib/json_api_kit/pagination/nulls_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/nulls_spec.rb
index e7c0e6f62c4..54699291c00 100644
--- a/spec/lib/json_api_kit/pagination/nulls_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/nulls_spec.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Nulls do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Nulls do
subject(:nulls) { described_class.for(placement, direction:) }
let(:placement) { :last }
- let(:direction) { JsonApiKit::Pagination::Direction.for(:asc) }
+ let(:direction) { JsonApiKit::Adapters::ActiveRecord::Pagination::Direction.for(:asc) }
describe ".for" do
context "when nulls cannot sort at that placement" do
@@ -133,7 +133,7 @@ RSpec.describe JsonApiKit::Pagination::Nulls do
end
context "when the direction sorts descending" do
- let(:direction) { JsonApiKit::Pagination::Direction.for(:desc) }
+ let(:direction) { JsonApiKit::Adapters::ActiveRecord::Pagination::Direction.for(:desc) }
it { is_expected.to be_read_first }
end
diff --git a/spec/lib/json_api_kit/pagination/numbered_rows_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/numbered_rows_spec.rb
similarity index 84%
rename from spec/lib/json_api_kit/pagination/numbered_rows_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/numbered_rows_spec.rb
index 154ff01c347..39ec97f719f 100644
--- a/spec/lib/json_api_kit/pagination/numbered_rows_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/numbered_rows_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::NumberedRows do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::NumberedRows do
subject(:numbered_rows) { described_class.new(scope, owner_key: :topic_id, keyset:, size:) }
fab!(:topic)
@@ -8,9 +8,9 @@ RSpec.describe JsonApiKit::Pagination::NumberedRows do
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(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key }
let(:keys) { [key.new(:post_number, model: Post), key.new(:id, model: Post)] }
- let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
let(:scope) { Post.where(topic_id: [topic.id, other_topic.id]) }
let(:size) { 1 }
diff --git a/spec/lib/json_api_kit/pagination/order/position_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/order/position_spec.rb
similarity index 56%
rename from spec/lib/json_api_kit/pagination/order/position_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/order/position_spec.rb
index d9ceff8f1f2..6e559eb6061 100644
--- a/spec/lib/json_api_kit/pagination/order/position_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/order/position_spec.rb
@@ -1,22 +1,24 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Order::Position do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Order::Position do
subject(:position) { described_class.new(segment:, values:) }
fab!(:topic)
let(:model) { Topic }
- let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:key) { JsonApiKit::Adapters::ActiveRecord::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(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
+ let(:order) { JsonApiKit::Adapters::ActiveRecord::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]) }
+ let(:cursor) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new([order.digest, 1, topic.id])
+ end
it "returns a position in the segment the cursor names" do
expect(position.segment).to eq(order.fetch(1))
@@ -28,19 +30,25 @@ RSpec.describe JsonApiKit::Pagination::Order::Position do
end
describe ".new" do
- context "with fewer values than the segment compares" do
+ context "when the position has too few values" do
let(:values) { [] }
- it "refuses them" do
- expect { position }.to raise_error(ArgumentError)
+ it "reports the expected value count" do
+ expect { position }.to raise_error(
+ ArgumentError,
+ "Incorrect number of values for this order segment: expected 1, received 0.",
+ )
end
end
- context "with more values than the segment compares" do
+ context "when the position has too many values" do
let(:values) { [topic.pinned_at, topic.id] }
- it "refuses them" do
- expect { position }.to raise_error(ArgumentError)
+ it "reports the expected value count" do
+ expect { position }.to raise_error(
+ ArgumentError,
+ "Incorrect number of values for this order segment: expected 1, received 2.",
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/pagination/order/segment_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/order/segment_spec.rb
similarity index 89%
rename from spec/lib/json_api_kit/pagination/order/segment_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/order/segment_spec.rb
index baef24da7e5..d8af58e6ee1 100644
--- a/spec/lib/json_api_kit/pagination/order/segment_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/order/segment_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Order::Segment do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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)) }
@@ -9,7 +9,9 @@ RSpec.describe JsonApiKit::Pagination::Order::Segment do
let(:model) { Topic }
let(:keyset) do
- JsonApiKit::Pagination::Keyset.new([JsonApiKit::Pagination::Keyset::Key.new(:id, model:)])
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::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]) }
@@ -20,9 +22,9 @@ RSpec.describe JsonApiKit::Pagination::Order::Segment do
describe ".split" do
subject(:segments) { described_class.split(keyset) }
- let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key }
let(:keys) { [key.new(:created_at, model:, direction: :desc), key.new(:id, model:)] }
- let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
let(:unpinned_ids) { [unpinned_topic.id, other_unpinned.id] }
context "when the leading key cannot be null" do
@@ -159,15 +161,17 @@ RSpec.describe JsonApiKit::Pagination::Order::Segment do
context "when the segment compares a timestamp" do
let(:keyset) do
- JsonApiKit::Pagination::Keyset.new(
- [JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:)],
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::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)
+ expect(JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.parse(cursor.to_s)).to eq(
+ cursor,
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/pagination/order/segments_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/order/segments_spec.rb
similarity index 89%
rename from spec/lib/json_api_kit/pagination/order/segments_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/order/segments_spec.rb
index 8ed06745714..f1e4f439799 100644
--- a/spec/lib/json_api_kit/pagination/order/segments_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/order/segments_spec.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Order::Segments do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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(:key) { JsonApiKit::Adapters::ActiveRecord::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(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
let(:scope) { Topic.where(id: [pinned_topic.id, unpinned_topic.id]) }
describe "#fetch" do
diff --git a/spec/lib/json_api_kit/pagination/order_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/order_spec.rb
similarity index 77%
rename from spec/lib/json_api_kit/pagination/order_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/order_spec.rb
index a1a058aaa57..a69b539141f 100644
--- a/spec/lib/json_api_kit/pagination/order_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/order_spec.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Order do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key }
let(:keys) { [key.new(:created_at, model:, direction: :desc), key.new(:id, model:)] }
- let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
let(:scope) { Topic.where(id: [pinned_topic.id, unpinned_topic.id]) }
it { is_expected.to delegate_method(:leading).to(:keyset) }
@@ -21,7 +21,7 @@ RSpec.describe JsonApiKit::Pagination::Order do
describe "#compatible_with?" do
let(:cursor) do
- JsonApiKit::Pagination::Cursor.new(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
[order.digest, 0, pinned_topic.created_at, pinned_topic.id],
)
end
@@ -32,7 +32,9 @@ RSpec.describe JsonApiKit::Pagination::Order do
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])
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
+ [order.digest, 7, pinned_topic.created_at, 1],
+ )
end
it "refuses the cursor" do
@@ -41,7 +43,11 @@ RSpec.describe JsonApiKit::Pagination::Order do
end
context "when the cursor holds another number of values" do
- let(:cursor) { JsonApiKit::Pagination::Cursor.new([order.digest, 0, pinned_topic.id]) }
+ let(:cursor) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
+ [order.digest, 0, pinned_topic.id],
+ )
+ end
it "refuses the cursor" do
expect(order).not_to be_compatible_with(cursor:)
@@ -116,14 +122,22 @@ RSpec.describe JsonApiKit::Pagination::Order 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]) }
+ let(:cursor) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
+ [order.digest, 1, unpinned_topic.id],
+ )
+ end
- before { allow(JsonApiKit::Pagination::Order::Position).to receive(:from) }
+ before do
+ allow(JsonApiKit::Adapters::ActiveRecord::Pagination::Order::Position).to receive(:from)
+ end
it "places the cursor in this order" do
order.position(cursor)
- expect(JsonApiKit::Pagination::Order::Position).to have_received(:from).with(cursor, order:)
+ expect(JsonApiKit::Adapters::ActiveRecord::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/adapters/active_record/pagination/page_per_owner_spec.rb
similarity index 77%
rename from spec/lib/json_api_kit/pagination/page_per_owner_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/page_per_owner_spec.rb
index 800b0ee4e4c..cf6fea0db80 100644
--- a/spec/lib/json_api_kit/pagination/page_per_owner_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/page_per_owner_spec.rb
@@ -1,14 +1,18 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::PagePerOwner do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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(:key) { JsonApiKit::Adapters::ActiveRecord::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(:order) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Order.new(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys),
+ )
+ end
let(:scope) { Post.where(topic_id: topic.id) }
describe ".new" do
diff --git a/spec/lib/json_api_kit/pagination/paginator_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/paginator_spec.rb
similarity index 90%
rename from spec/lib/json_api_kit/pagination/paginator_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/paginator_spec.rb
index 8d0ca1f3d32..7b3769a34c3 100644
--- a/spec/lib/json_api_kit/pagination/paginator_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/paginator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Paginator do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Paginator do
subject(:paginator) { described_class.for(scope, order:, size:, after:, before:) }
fab!(:first_topic, :topic)
@@ -12,8 +12,10 @@ RSpec.describe JsonApiKit::Pagination::Paginator do
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:)]),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Order.new(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:)],
+ ),
)
end
let(:scope) { Topic.where(id: topics.map(&:id)) }
@@ -52,7 +54,10 @@ RSpec.describe JsonApiKit::Pagination::Paginator do
let(:before) { fourth_cursor }
it "refuses the request" do
- expect { paginator }.to raise_error(ArgumentError)
+ expect { paginator }.to raise_error(
+ ArgumentError,
+ "Cannot specify both before and after cursors.",
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null_spec.rb
similarity index 76%
rename from spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null_spec.rb
index 3e4ab4d7aa5..f337b7a8fd7 100644
--- a/spec/lib/json_api_kit/pagination/predicate/term/null_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term/null_spec.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Predicate::Term::Null do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Predicate::Term::Null do
subject(:term) { described_class.new(key) }
let(:model) { Topic }
- let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:bumped_at, model:) }
+ let(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:bumped_at, model:) }
describe "#comparable?" do
it { is_expected.not_to be_comparable }
@@ -28,7 +28,13 @@ RSpec.describe JsonApiKit::Pagination::Predicate::Term::Null do
end
context "when the order reads the nulls first" do
- let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:bumped_at, model:, nulls: :first) }
+ let(:key) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :bumped_at,
+ model:,
+ nulls: :first,
+ )
+ end
it "returns one comparison for the rows that hold a value" do
expect(disjuncts).to eq([%(("topics"."bumped_at" IS NOT NULL))])
diff --git a/spec/lib/json_api_kit/pagination/predicate/term_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term_spec.rb
similarity index 79%
rename from spec/lib/json_api_kit/pagination/predicate/term_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term_spec.rb
index 1c0423cbeab..a2158c1d5c7 100644
--- a/spec/lib/json_api_kit/pagination/predicate/term_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate/term_spec.rb
@@ -1,12 +1,16 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Predicate::Term do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:) }
let(:descending_key) do
- JsonApiKit::Pagination::Keyset::Key.new(:created_at, model:, direction: :desc)
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :created_at,
+ model:,
+ direction: :desc,
+ )
end
let(:value) { "2026-08-03T12:00:00.123456Z" }
@@ -24,7 +28,7 @@ RSpec.describe JsonApiKit::Pagination::Predicate::Term do
end
context "when the cursor holds false for the key" do
- let(:key) { JsonApiKit::Pagination::Keyset::Key.new(:closed, model:) }
+ let(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:closed, model:) }
let(:value) { false }
it "returns a term that compares the false value" do
@@ -37,7 +41,13 @@ RSpec.describe JsonApiKit::Pagination::Predicate::Term 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) }
+ let(:key) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ nulls: :last,
+ )
+ end
it { is_expected.not_to be_comparable }
end
@@ -70,7 +80,12 @@ RSpec.describe JsonApiKit::Pagination::Predicate::Term do
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)]
+ [
+ described_class.for(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
+ 12,
+ ),
+ ]
end
it "adds an equality for each key before it" do
diff --git a/spec/lib/json_api_kit/pagination/predicate_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate_spec.rb
similarity index 63%
rename from spec/lib/json_api_kit/pagination/predicate_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/predicate_spec.rb
index 9ce180a6122..5acd22c5730 100644
--- a/spec/lib/json_api_kit/pagination/predicate_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/predicate_spec.rb
@@ -1,16 +1,20 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Predicate do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :created_at,
+ model:,
+ direction: :desc,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
- let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
+ let(:keyset) { JsonApiKit::Adapters::ActiveRecord::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) }
@@ -18,13 +22,20 @@ RSpec.describe JsonApiKit::Pagination::Predicate 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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ nulls: :last,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
it "refuses to build the predicate" do
- expect { predicate }.to raise_error(ArgumentError)
+ expect { predicate }.to raise_error(
+ ArgumentError,
+ "Pagination predicates require a single order segment.",
+ )
end
end
end
@@ -44,7 +55,7 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
end
context "when the order has one key" do
- let(:keys) { [JsonApiKit::Pagination::Keyset::Key.new(:id, model:)] }
+ let(:keys) { [JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:)] }
let(:record) { Topic.new(id: 12) }
it "compares that key and adds no bound" do
@@ -55,8 +66,8 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
@@ -68,14 +79,14 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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(
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
:bumped_at,
model:,
direction: :desc,
nulls: :last,
),
- JsonApiKit::Pagination::Keyset::Key.new(:id, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3), bumped_at: nil) }
@@ -92,9 +103,13 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ nulls: :last,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
let(:record) do
@@ -113,9 +128,13 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ nulls: :first,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
let(:record) { Topic.new(id: 12, created_at: Time.utc(2026, 8, 3), pinned_at: nil) }
@@ -128,8 +147,12 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:closed, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :id,
+ model:,
+ direction: :desc,
+ ),
]
end
let(:record) { Topic.new(id: 12, closed: false) }
@@ -142,8 +165,8 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:bumped_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
let(:record) { Topic.new(id: 12, bumped_at: nil) }
@@ -176,9 +199,14 @@ RSpec.describe JsonApiKit::Pagination::Predicate do
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:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:created_at, model:),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ direction: :desc,
+ nulls: :last,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
]
end
let(:scope) do
diff --git a/spec/lib/json_api_kit/pagination/row_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/row_spec.rb
similarity index 65%
rename from spec/lib/json_api_kit/pagination/row_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/row_spec.rb
index 98bfa0faf26..ef9186c00e8 100644
--- a/spec/lib/json_api_kit/pagination/row_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/row_spec.rb
@@ -1,15 +1,19 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Row do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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:)])
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:)],
+ )
+ end
+ let(:segment) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Order::Segment.new(id: 2, keyset:)
end
- let(:segment) { JsonApiKit::Pagination::Order::Segment.new(id: 2, keyset:) }
describe "#record" do
it "returns the record it holds" do
diff --git a/spec/lib/json_api_kit/adapters/active_record/pagination/scan_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/scan_spec.rb
new file mode 100644
index 00000000000..8a665d23f30
--- /dev/null
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/scan_spec.rb
@@ -0,0 +1,135 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:)],
+ )
+ end
+ let(:segment) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Order::Segment.new(id: 3, keyset:)
+ end
+ 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::Adapters::ActiveRecord::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
+
+ describe "#next_in" do
+ subject(:next_scan) { scan.next_in(order) }
+
+ fab!(:pinned_topic) { Fabricate(:topic, pinned_at: Time.utc(2026, 8, 1)) }
+
+ let(:keyset) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(
+ [
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(
+ :pinned_at,
+ model:,
+ direction: :desc,
+ nulls: :last,
+ ),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key.new(:id, model:),
+ ],
+ )
+ end
+ let(:order) { JsonApiKit::Adapters::ActiveRecord::Pagination::Order.new(keyset) }
+ let(:segment) { order.first }
+ let(:scope) { super().or(Topic.where(id: pinned_topic.id)) }
+ let(:next_records) { next_scan.rows.map(&:record) }
+
+ it "reads the remaining page capacity from the next segment" do
+ expect(next_records).to eq([first_topic])
+ end
+
+ context "when the scan has more rows than the page holds" do
+ let(:size) { 0 }
+
+ it "returns no next scan" do
+ expect(next_scan).to be_nil
+ end
+ end
+
+ context "when the scan exhausts the last segment" do
+ let(:segment) { order.segments.last }
+ let(:size) { 3 }
+
+ it "returns no next scan" do
+ expect(next_scan).to be_nil
+ end
+ end
+
+ context "when the cursor skips the first segment" do
+ let(:after) { segment.position_of(pinned_topic).values }
+
+ it "reads the next segment from its start" do
+ expect(next_records).to eq([first_topic, second_topic])
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/pagination/window_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination/window_spec.rb
similarity index 76%
rename from spec/lib/json_api_kit/pagination/window_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination/window_spec.rb
index 5238a1a87b4..84fe304595b 100644
--- a/spec/lib/json_api_kit/pagination/window_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination/window_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination::Window do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination::Window do
subject(:window) { described_class.new(scope, order:, size:, after:) }
fab!(:first_topic, :topic)
@@ -8,10 +8,10 @@ RSpec.describe JsonApiKit::Pagination::Window do
fab!(:third_topic, :topic)
let(:model) { Topic }
- let(:key) { JsonApiKit::Pagination::Keyset::Key }
+ let(:key) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset::Key }
let(:keys) { [key.new(:id, model:)] }
- let(:keyset) { JsonApiKit::Pagination::Keyset.new(keys) }
- let(:order) { JsonApiKit::Pagination::Order.new(keyset) }
+ let(:keyset) { JsonApiKit::Adapters::ActiveRecord::Pagination::Keyset.new(keys) }
+ let(:order) { JsonApiKit::Adapters::ActiveRecord::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 }
@@ -72,28 +72,6 @@ RSpec.describe JsonApiKit::Pagination::Window 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) }
diff --git a/spec/lib/json_api_kit/pagination_spec.rb b/spec/lib/json_api_kit/adapters/active_record/pagination_spec.rb
similarity index 97%
rename from spec/lib/json_api_kit/pagination_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/pagination_spec.rb
index 6e105a7f23c..e7b458f7c6b 100644
--- a/spec/lib/json_api_kit/pagination_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/pagination_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Pagination do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Pagination do
fab!(:first_pinned) do
Fabricate(:topic, created_at: Time.utc(2026, 8, 1), pinned_at: Time.utc(2026, 7, 1))
end
diff --git a/spec/lib/json_api_kit/query/collection_spec.rb b/spec/lib/json_api_kit/adapters/active_record/query/collection_spec.rb
similarity index 91%
rename from spec/lib/json_api_kit/query/collection_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/query/collection_spec.rb
index a59717c58b8..5543bbb6140 100644
--- a/spec/lib/json_api_kit/query/collection_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/query/collection_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Query::Collection do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Query::Collection do
subject(:query) { described_class.new(resource, request, scoped_to:) }
fab!(:first_topic) do
@@ -147,6 +147,19 @@ RSpec.describe JsonApiKit::Query::Collection do
end
end
+ context "when field readability depends on the record" do
+ let(:resource_class) do
+ Class.new(super()) { attribute :views, readable: ->(_guardian, topic) { !topic.closed? } }
+ end
+ let(:params) { { fields: { topics: %w[views] } } }
+
+ it "reads the columns required by the readability rule" do
+ expect(query.records.first.attributes).to include(
+ JsonApiKit::Name::Field.new(value: "views", type: "topics") => first_topic.views,
+ )
+ end
+ end
+
context "when the fields hold a block attribute" do
let(:resource_class) do
Class.new(JsonApiKit::Resource) do
diff --git a/spec/lib/json_api_kit/query/individual_spec.rb b/spec/lib/json_api_kit/adapters/active_record/query/individual_spec.rb
similarity index 95%
rename from spec/lib/json_api_kit/query/individual_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/query/individual_spec.rb
index 3c18b9bb5bc..590efe2ab30 100644
--- a/spec/lib/json_api_kit/query/individual_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/query/individual_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Query::Individual do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Query::Individual do
subject(:reading) { described_class.new(resource, request) }
fab!(:topic) { Fabricate(:topic, title: "The row an id names") }
diff --git a/spec/lib/json_api_kit/reflection_spec.rb b/spec/lib/json_api_kit/adapters/active_record/reflection_spec.rb
similarity index 78%
rename from spec/lib/json_api_kit/reflection_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/reflection_spec.rb
index f69f4e5b005..21e61892d09 100644
--- a/spec/lib/json_api_kit/reflection_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/reflection_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Reflection do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Reflection do
subject(:reflection) { described_class.for(Topic.reflect_on_association(name)) }
fab!(:topic) { Fabricate(:topic, title: "A row the kit reflects on") }
@@ -40,12 +40,14 @@ RSpec.describe JsonApiKit::Reflection do
describe "#association" do
subject(:association) { reflection.association([topic]) }
- it { is_expected.to be_an_instance_of(JsonApiKit::Association) }
+ it { is_expected.to be_an_instance_of(JsonApiKit::Adapters::ActiveRecord::Association) }
context "with a through association" do
let(:name) { :tags }
- it { is_expected.to be_an_instance_of(JsonApiKit::Association::Through) }
+ it do
+ is_expected.to be_an_instance_of(JsonApiKit::Adapters::ActiveRecord::Association::Through)
+ end
end
end
end
diff --git a/spec/lib/json_api_kit/schema_spec.rb b/spec/lib/json_api_kit/adapters/active_record/schema_spec.rb
similarity index 87%
rename from spec/lib/json_api_kit/schema_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/schema_spec.rb
index 027599bef13..74a2b4719af 100644
--- a/spec/lib/json_api_kit/schema_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/schema_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Schema do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::Schema do
subject(:schema) { described_class.new(Topic) }
fab!(:topic) { Fabricate(:topic, title: "A row the kit asks about") }
@@ -47,12 +47,16 @@ RSpec.describe JsonApiKit::Schema do
describe "#association" do
it "returns an association between the two tables" do
- expect(schema.association(:user, [topic])).to be_an_instance_of(JsonApiKit::Association)
+ expect(schema.association(:user, [topic])).to be_an_instance_of(
+ JsonApiKit::Adapters::ActiveRecord::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)
+ expect(schema.association(:tags, [topic])).to be_a(
+ JsonApiKit::Adapters::ActiveRecord::Association::Through,
+ )
end
end
end
diff --git a/spec/lib/json_api_kit/scoping_spec.rb b/spec/lib/json_api_kit/adapters/active_record/scoping_spec.rb
similarity index 69%
rename from spec/lib/json_api_kit/scoping_spec.rb
rename to spec/lib/json_api_kit/adapters/active_record/scoping_spec.rb
index 27fe9f5dee1..d53e09073e7 100644
--- a/spec/lib/json_api_kit/scoping_spec.rb
+++ b/spec/lib/json_api_kit/adapters/active_record/scoping_spec.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-RSpec.describe JsonApiKit::Scoping do
+RSpec.describe JsonApiKit::Adapters::ActiveRecord::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 }
+ let(:requested) { JsonApiKit::Adapters::ActiveRecord::Page::Requested.for }
describe "#apply" do
it "keeps a listing to those rows" do
@@ -29,10 +29,12 @@ RSpec.describe JsonApiKit::Scoping do
end
context "when a sideload keeps it to the rows a relationship reaches" do
- let(:scoped_to) { JsonApiKit::Schema.new(Topic).association(:posts, [topic]) }
+ let(:scoped_to) do
+ JsonApiKit::Adapters::ActiveRecord::Schema.new(Topic).association(:posts, [topic])
+ end
it "reads one page for each owner instead" do
- expect(scoping.page(requested)).to be_a(JsonApiKit::Page::PerOwner)
+ expect(scoping.page(requested)).to be_a(JsonApiKit::Adapters::ActiveRecord::Page::PerOwner)
end
end
end
diff --git a/spec/lib/json_api_kit/adapters/active_record_spec.rb b/spec/lib/json_api_kit/adapters/active_record_spec.rb
new file mode 100644
index 00000000000..fc3c6bf1797
--- /dev/null
+++ b/spec/lib/json_api_kit/adapters/active_record_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Adapters::ActiveRecord do
+ subject(:adapter) { resource.adapter }
+
+ fab!(:first_topic) { Fabricate(:topic, title: "First topic from the adapter's scope") }
+ fab!(:second_topic) { Fabricate(:topic, title: "Second topic from the adapter's scope") }
+ fab!(:third_topic) { Fabricate(:topic, title: "Third topic from the adapter's scope") }
+
+ let(:resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ filter :title
+ end
+ .new(guardian:)
+ end
+ let(:guardian) { Guardian.new }
+ let(:available_records) { [first_topic, second_topic, third_topic] }
+ let(:scope) { Topic.all }
+ let(:restricted_scope) { Topic.where(id: record.id) }
+ let(:empty_scope) { Topic.none }
+ let(:filter_name) { "title" }
+ let(:missing_id) { (Topic.maximum(:id) + 1).to_s }
+ let(:params) { {} }
+ let(:request) do
+ JsonApiKit::Request::Collection.new(params, guardian:, edition: JsonApiKit::Edition.current)
+ end
+
+ describe "#filter" do
+ subject(:matching_records) { adapter.filter(scope, filter_name, value).to_a }
+
+ context "when the value is an array" do
+ let(:value) { [first_topic.title, second_topic.title] }
+
+ it "keeps the rows whose column holds one of them" do
+ expect(matching_records).to contain_exactly(first_topic, second_topic)
+ end
+ end
+ end
+
+ describe "#requested_page" do
+ subject(:page) { adapter.requested_page(request) }
+
+ before { allow(described_class::Page::Requested).to receive(:from).and_call_original }
+
+ it "builds the requested page for this adapter" do
+ page
+
+ expect(described_class::Page::Requested).to have_received(:from).with(request, adapter:)
+ end
+ end
+
+ describe "#collection?" do
+ it "recognizes an ActiveRecord relation" do
+ expect(adapter).to be_a_collection(scope)
+ end
+ end
+
+ it_behaves_like "a resource adapter"
+end
diff --git a/spec/lib/json_api_kit/declarations/attribute_spec.rb b/spec/lib/json_api_kit/declarations/attribute_spec.rb
index 052a9c44f95..e59ae7e9a55 100644
--- a/spec/lib/json_api_kit/declarations/attribute_spec.rb
+++ b/spec/lib/json_api_kit/declarations/attribute_spec.rb
@@ -73,20 +73,4 @@ RSpec.describe JsonApiKit::Declarations::Attribute do
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
index f03472b196b..d8a76aaf0e5 100644
--- a/spec/lib/json_api_kit/declarations/attributes_spec.rb
+++ b/spec/lib/json_api_kit/declarations/attributes_spec.rb
@@ -1,33 +1,16 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Declarations::Attributes do
- subject(:attributes) { described_class.new(declarations, guardian:, schema:, type: "topics") }
+ subject(:attributes) { described_class.new(declarations, guardian:, type: "topics") }
fab!(:topic) { Fabricate(:topic, title: "A field rendered from a record", closed: false) }
let(:guardian) { Guardian.new }
- let(:schema) { JsonApiKit::Schema.new(Topic) }
let(:attribute) { JsonApiKit::Declarations::Attribute }
let(:declarations) { [attribute.new(:title), attribute.new(:closed)] }
let(:title) { JsonApiKit::Name::Field.new(value: "title", type: "topics") }
let(:closed) { JsonApiKit::Name::Field.new(value: "closed", type: "topics") }
- 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) }
diff --git a/spec/lib/json_api_kit/declarations/fields_spec.rb b/spec/lib/json_api_kit/declarations/fields_spec.rb
index 217250e36e4..062ad68114b 100644
--- a/spec/lib/json_api_kit/declarations/fields_spec.rb
+++ b/spec/lib/json_api_kit/declarations/fields_spec.rb
@@ -2,14 +2,13 @@
RSpec.describe JsonApiKit::Declarations::Fields do
subject(:fields) do
- described_class.for(names, guardian:, attributes:, relationships:, schema:, type: "topics")
+ described_class.for(names, guardian:, attributes:, relationships:, type: "topics")
end
let(:guardian) { Guardian.new }
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
[
@@ -29,7 +28,10 @@ RSpec.describe JsonApiKit::Declarations::Fields do
end
it "raises a collision" do
- expect { fields }.to raise_error(described_class::Collision, /title/)
+ expect { fields }.to raise_error(
+ described_class::Collision,
+ "Duplicate field names: title.",
+ )
end
end
@@ -42,7 +44,10 @@ RSpec.describe JsonApiKit::Declarations::Fields do
end
it "raises a collision" do
- expect { fields }.to raise_error(described_class::Collision, /title/)
+ expect { fields }.to raise_error(
+ described_class::Collision,
+ "Duplicate field names: title.",
+ )
end
end
@@ -55,7 +60,10 @@ RSpec.describe JsonApiKit::Declarations::Fields do
end
it "raises a collision" do
- expect { fields }.to raise_error(described_class::Collision, /id, type/)
+ expect { fields }.to raise_error(
+ described_class::Collision,
+ "Cannot declare reserved field names: id, type.",
+ )
end
end
end
@@ -123,28 +131,4 @@ RSpec.describe JsonApiKit::Declarations::Fields do
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
deleted file mode 100644
index e74c00715a2..00000000000
--- a/spec/lib/json_api_kit/declarations/filter/equality_spec.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# 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
index 7cc6c2da59c..19348404dd9 100644
--- a/spec/lib/json_api_kit/declarations/filter_spec.rb
+++ b/spec/lib/json_api_kit/declarations/filter_spec.rb
@@ -1,41 +1,35 @@
# 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 }
+ subject(:filter) { described_class.new(:title) { |titles, value| titles.reject { it == value } } }
describe "#name" do
subject(:name) { filter.name }
- it "returns the name a request filters by" do
+ it "returns the filter name" 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
+ subject(:filtered_titles) { filter.apply(scope, value, adapter:) }
- context "when the filter declares no condition of its own" do
- subject(:filter) { described_class.new(:title) }
+ let(:scope) { [value, other_title] }
+ let(:value) { "First topic" }
+ let(:other_title) { "Second topic" }
+ let(:adapter) { instance_double(JsonApiKit::Adapters::ActiveRecord) }
- let(:equality) { instance_spy(described_class::Equality) }
+ before { allow(adapter).to receive(:filter).with(scope, "title", value).and_return([value]) }
- before do
- allow(described_class::Equality).to receive(:new).with("title").and_return(equality)
- end
+ it "applies the declared condition" do
+ expect(filtered_titles).to contain_exactly(other_title)
+ end
- it "compares the column of its own name to the value" do
- filter.apply(scope, matching_topic.title)
+ context "when the filter declares no condition of its own" do
+ let(:filter) { described_class.new(:title) }
- expect(equality).to have_received(:call).with(scope, matching_topic.title)
+ it "returns the adapter's matching rows" do
+ expect(filtered_titles).to contain_exactly(value)
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
index 9507084228a..98207387214 100644
--- a/spec/lib/json_api_kit/declarations/filters_spec.rb
+++ b/spec/lib/json_api_kit/declarations/filters_spec.rb
@@ -3,15 +3,8 @@
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") }
@@ -37,38 +30,57 @@ RSpec.describe JsonApiKit::Declarations::Filters do
end
it "preserves the original collection" do
- combined.names
- expect(filters.names).to contain_exactly("title", "closed")
+ expect { combined.names }.not_to change(filters, :names)
end
end
describe "#apply" do
- subject(:kept_ids) { filters.apply(scope, filtering).map(&:id) }
-
- let(:filtering) { { "closed" => "false" } }
+ subject(:matching_topics) { filters.apply(scope, filtering, adapter:) }
+
+ let(:open_topic) { { title: "First topic", closed: false } }
+ let(:another_open_topic) { { title: "Second topic", closed: false } }
+ let(:closed_topic) { { title: "Closed topic", closed: true } }
+ let(:scope) { [open_topic, another_open_topic, closed_topic] }
+ let(:open_topics) { [open_topic, another_open_topic] }
+ let(:adapter) { instance_double(JsonApiKit::Adapters::ActiveRecord) }
+ let(:filtering) { { "closed" => false } }
+
+ before do
+ allow(adapter).to receive(:filter).with(scope, "closed", false).and_return(open_topics)
+ end
it "narrows the scope by that filter" do
- expect(kept_ids).to contain_exactly(open_topic.id, another_open_topic.id)
+ expect(matching_topics).to contain_exactly(open_topic, another_open_topic)
end
context "when the filtering holds two filters" do
- let(:filtering) { { "closed" => "false", "title" => open_topic.title } }
+ let(:filtering) { super().merge("title" => open_topic.fetch(:title)) }
+
+ before do
+ allow(adapter).to receive(:filter).with(
+ open_topics,
+ "title",
+ open_topic.fetch(:title),
+ ).and_return([open_topic])
+ end
it "keeps only the rows every one of them allows" do
- expect(kept_ids).to contain_exactly(open_topic.id)
+ expect(matching_topics).to contain_exactly(open_topic)
end
end
context "when there is no filtering" do
+ let(:filtering) { {} }
+
it "returns the same scope" do
- expect(filters.apply(scope)).to be(scope)
+ expect(matching_topics).to be(scope)
end
context "when declarations are evaluated lazily" do
let(:declarations) { Enumerator.new { raise "Filters were evaluated." } }
it "returns the scope without evaluating the declarations" do
- expect(filters.apply(scope)).to be(scope)
+ expect(matching_topics).to be(scope)
end
end
end
@@ -77,7 +89,7 @@ RSpec.describe JsonApiKit::Declarations::Filters do
let(:filtering) { { secrets: "x" } }
it "refuses the request" do
- expect { kept_ids }.to raise_error(KeyError)
+ expect { matching_topics }.to raise_error(KeyError)
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
index 9ff9688a3df..4f7aabef48c 100644
--- a/spec/lib/json_api_kit/declarations/relationship_spec.rb
+++ b/spec/lib/json_api_kit/declarations/relationship_spec.rb
@@ -5,10 +5,17 @@ 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
- let(:guardian) { Guardian.new }
+ Class.new(JsonApiKit::Resource) do
+ model User
+ type :users
+ attribute :username
+ has_many :groups, resource: related
+ end
+ end
describe ".new" do
context "when the readable block declares both a guardian and a record" do
@@ -26,44 +33,7 @@ RSpec.describe JsonApiKit::Declarations::Relationship do
end
end
- 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:, edition:) }
-
- 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) }
- let(:edition) { JsonApiKit::Edition.current }
-
- 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:, edition:)
- 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) }
@@ -75,72 +45,26 @@ RSpec.describe JsonApiKit::Declarations::Relationship do
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(guardian:),
- type: "posts",
- )
- end,
- )
- end
+ let(:first_record) { instance_double(JsonApiKit::Record) }
+ let(:second_record) { instance_double(JsonApiKit::Record, cursor: "next-cursor") }
+ let(:third_record) { instance_double(JsonApiKit::Record) }
+ let(:records) { JsonApiKit::Records.new([first_record, second_record, third_record]) }
it "holds one page of them at the size the resource reads" do
- expect(linkage.records.map(&:record)).to eq([first_post, second_post])
+ expect(linkage.records.to_a).to eq([first_record, second_record])
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
index e3752a997c5..0fd2d4d7b16 100644
--- a/spec/lib/json_api_kit/declarations/sorts_spec.rb
+++ b/spec/lib/json_api_kit/declarations/sorts_spec.rb
@@ -1,14 +1,12 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Declarations::Sorts do
- subject(:sorts) { described_class.new(declarations, schema:, unique_by:) }
+ subject(:sorts) { described_class.new(declarations) }
- 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(:unique_by) { [] }
describe "#fetch" do
subject(:sort) { sorts.fetch("created_at") }
@@ -29,91 +27,12 @@ RSpec.describe JsonApiKit::Declarations::Sorts do
describe "#with" do
subject(:combined) { sorts.with([sort_class.new(:title)]) }
- let(:unique_by) { %i[created_at id] }
-
it "combines current and additional declarations" do
expect(combined.names).to contain_exactly("created_at", "ran_at", "title")
end
- it "preserves the unique keys" do
- expect(combined.keyset("title" => :desc).keys.map(&:name)).to eq(%i[title created_at id])
- end
-
it "preserves the original collection" do
expect { combined.names }.not_to change(sorts, :names)
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 the ordering is empty" 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/default_sort_spec.rb b/spec/lib/json_api_kit/default_sort_spec.rb
index 26dd682af09..770a7e07a45 100644
--- a/spec/lib/json_api_kit/default_sort_spec.rb
+++ b/spec/lib/json_api_kit/default_sort_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe JsonApiKit::DefaultSort do
let(:ordering) { { created_at: :sideways } }
it "rejects the direction" do
- expect { default_sort }.to raise_error(ArgumentError, /unknown direction: sideways/)
+ expect { default_sort }.to raise_error(ArgumentError, /Unknown sort direction: :sideways/)
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
index b3455e6efb0..051103a9807 100644
--- a/spec/lib/json_api_kit/document/contents_spec.rb
+++ b/spec/lib/json_api_kit/document/contents_spec.rb
@@ -16,13 +16,12 @@ RSpec.describe JsonApiKit::Document::Contents do
def record_of(model, type, relationships = {})
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: model, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: model, segment: nil),
JsonApiKit::Declarations::Fields.for(
nil,
guardian:,
attributes: [],
relationships: [],
- schema: JsonApiKit::Schema.new(model.class),
type:,
),
type:,
diff --git a/spec/lib/json_api_kit/document/relationship_object_spec.rb b/spec/lib/json_api_kit/document/relationship_object_spec.rb
index e55d175cb7d..fb521754728 100644
--- a/spec/lib/json_api_kit/document/relationship_object_spec.rb
+++ b/spec/lib/json_api_kit/document/relationship_object_spec.rb
@@ -27,14 +27,14 @@ RSpec.describe JsonApiKit::Document::RelationshipObject do
end
let(:record) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: author, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: author, segment: nil),
users_resource.fields(guardian:),
type: "users",
)
end
let(:owner) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil),
topics_resource.fields(guardian:),
type: "topics",
namespace:,
diff --git a/spec/lib/json_api_kit/document/resource_object_spec.rb b/spec/lib/json_api_kit/document/resource_object_spec.rb
index 20e9cde8b22..31f3f739af0 100644
--- a/spec/lib/json_api_kit/document/resource_object_spec.rb
+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb
@@ -16,7 +16,7 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
end
end
let(:fields) { resource.fields(guardian:) }
- let(:row) { JsonApiKit::Pagination::Row.new(record: topic, segment: nil) }
+ let(:row) { JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil) }
let(:record) { JsonApiKit::Record.new(row, fields, type: "topics") }
let(:meta) { {} }
let(:urls) do
@@ -88,7 +88,7 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
let(:linkage) { JsonApiKit::Linkage::ToOne.new([author_record]) }
let(:author_record) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: topic.user, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic.user, segment: nil),
users_resource.fields(guardian:),
type: "users",
)
@@ -151,7 +151,7 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
end
let(:post_record) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: post, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: post, segment: nil),
posts_resource.fields(guardian:),
type: "posts",
)
diff --git a/spec/lib/json_api_kit/document_spec.rb b/spec/lib/json_api_kit/document_spec.rb
index 1fa4292c655..fc8d8f67d87 100644
--- a/spec/lib/json_api_kit/document_spec.rb
+++ b/spec/lib/json_api_kit/document_spec.rb
@@ -33,13 +33,13 @@ RSpec.describe JsonApiKit::Document do
let(:input) do
JsonApiKit::Request::Input::Individual.new(parameters, resource: instance, edition:)
end
- let(:rendered_ids) { document.to_h[:data].map { it[:id] } }
+ let(:rendered_ids) { document.to_h.fetch(:data).map { it.fetch(:id) } }
context "when the input is a record" do
let(:value) { topic }
it "renders an individual resource" do
- expect(document.to_h[:data]).to include(id: topic.id.to_s)
+ expect(document.to_h.fetch(:data)).to include(id: topic.id.to_s)
end
end
@@ -63,7 +63,7 @@ RSpec.describe JsonApiKit::Document do
let(:value) { [] }
it "renders an empty collection" do
- expect(document.to_h[:data]).to eq([])
+ expect(document.to_h.fetch(:data)).to be_empty
end
end
@@ -77,6 +77,16 @@ RSpec.describe JsonApiKit::Document do
end
end
+ context "when the adapter recognizes another collection type" do
+ let(:value) { [other_topic, topic].each }
+
+ before { allow(instance.adapter).to receive(:collection?).with(value).and_return(true) }
+
+ it "preserves the supplied collection order" do
+ expect(rendered_ids).to eq([other_topic.id.to_s, topic.id.to_s])
+ end
+ end
+
context "when the input is an existing document" do
subject(:document) { described_class.from(value) { raise "Unexpected request context" } }
@@ -104,7 +114,7 @@ RSpec.describe JsonApiKit::Document do
end
let(:scoped_to) { nil }
- let(:listed_ids) { document.to_h[:data].map { it[:id] } }
+ let(:listed_ids) { document.to_h.fetch(:data).map { it.fetch(:id) } }
it "renders every record of the listing" do
expect(listed_ids).to eq([topic.id.to_s, other_topic.id.to_s])
@@ -120,28 +130,18 @@ RSpec.describe JsonApiKit::Document do
before do
allow(resource).to receive(:new).and_return(instance)
allow(JsonApiKit::Request::Input::Collection).to receive(:new).and_call_original
- allow(JsonApiKit::Query::Collection).to receive(:new).and_call_original
+ allow(instance).to receive(:all).and_call_original
document
end
- it "uses the instance for input validation" do
+ it "reuses one resource for validation and execution", :aggregate_failures do
+ expect(resource).to have_received(:new).with(guardian:, edition:).once
expect(JsonApiKit::Request::Input::Collection).to have_received(:new).with(
parameters,
resource: instance,
edition:,
)
- end
-
- it "uses the same instance for execution" do
- expect(JsonApiKit::Query::Collection).to have_received(:new).with(
- instance,
- an_instance_of(JsonApiKit::Request::Collection),
- scoped_to:,
- )
- end
-
- it "creates one instance for the request" do
- expect(resource).to have_received(:new).once
+ expect(instance).to have_received(:all).once
end
end
@@ -156,30 +156,21 @@ RSpec.describe JsonApiKit::Document do
end
let(:resource) { Class.new(super()).tap { it.has_one(:user, resource: users_resource) } }
let(:users) { users_resource.new(guardian:, edition:) }
+ let(:included_ids) { document.to_h.fetch(:included).map { it.fetch(:id) } }
before do
allow(users_resource).to receive(:new).and_return(users)
- allow(JsonApiKit::Query::Collection).to receive(:new).and_call_original
+ allow(users).to receive(:all).and_call_original
document
end
- it "creates one resource instance for the related listing" do
+ it "reuses one resource for the related listing", :aggregate_failures do
expect(users_resource).to have_received(:new).with(guardian:, edition:).once
- end
-
- it "queries the related records through that instance" do
- expect(JsonApiKit::Query::Collection).to have_received(:new).with(
- users,
- an_instance_of(JsonApiKit::Request::Collection),
- scoped_to: an_instance_of(JsonApiKit::Scoping::PerOwner),
- )
+ expect(users).to have_received(:all).once
end
it "renders all related records" do
- expect(document.to_h[:included].map { it[:id] }).to contain_exactly(
- topic.user_id.to_s,
- other_topic.user_id.to_s,
- )
+ expect(included_ids).to contain_exactly(topic.user_id.to_s, other_topic.user_id.to_s)
end
end
@@ -197,7 +188,7 @@ RSpec.describe JsonApiKit::Document do
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")
+ expect(document.to_h.fetch(:errors).sole).to include(status: "400", title: "No such sort")
end
end
end
@@ -208,7 +199,7 @@ RSpec.describe JsonApiKit::Document do
let(:id) { topic.id }
it "renders the record as a document" do
- expect(document.to_h[:data][:id]).to eq(topic.id.to_s)
+ expect(document.to_h.dig(:data, :id)).to eq(topic.id.to_s)
end
context "when the resource supplies request context" do
@@ -217,27 +208,18 @@ RSpec.describe JsonApiKit::Document do
before do
allow(resource).to receive(:new).and_return(instance)
allow(JsonApiKit::Request::Input::Individual).to receive(:new).and_call_original
- allow(JsonApiKit::Query::Individual).to receive(:new).and_call_original
+ allow(instance).to receive(:find).and_call_original
document
end
- it "uses the instance for input validation" do
+ it "reuses one resource for validation and execution", :aggregate_failures do
+ expect(resource).to have_received(:new).with(guardian:, edition:).once
expect(JsonApiKit::Request::Input::Individual).to have_received(:new).with(
parameters,
resource: instance,
edition:,
)
- end
-
- it "uses the same instance for execution" do
- expect(JsonApiKit::Query::Individual).to have_received(:new).with(
- instance,
- an_instance_of(JsonApiKit::Request::Individual),
- )
- end
-
- it "creates one instance for the request" do
- expect(resource).to have_received(:new).once
+ expect(instance).to have_received(:find).once
end
end
@@ -247,7 +229,7 @@ RSpec.describe JsonApiKit::Document do
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")
+ expect(document.to_h.fetch(:errors).sole).to include(status: "404", title: "No such record")
end
end
end
diff --git a/spec/lib/json_api_kit/included_spec.rb b/spec/lib/json_api_kit/included_spec.rb
index 03953e468d8..c102980dd6d 100644
--- a/spec/lib/json_api_kit/included_spec.rb
+++ b/spec/lib/json_api_kit/included_spec.rb
@@ -14,13 +14,12 @@ RSpec.describe JsonApiKit::Included do
def record_of(model, type, relationships = {})
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: model, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: model, segment: nil),
JsonApiKit::Declarations::Fields.for(
nil,
guardian:,
attributes: [],
relationships: [],
- schema: JsonApiKit::Schema.new(model.class),
type:,
),
type:,
diff --git a/spec/lib/json_api_kit/linkage/to_many_spec.rb b/spec/lib/json_api_kit/linkage/to_many_spec.rb
index 892f3c74c70..4e4389d8814 100644
--- a/spec/lib/json_api_kit/linkage/to_many_spec.rb
+++ b/spec/lib/json_api_kit/linkage/to_many_spec.rb
@@ -14,14 +14,14 @@ RSpec.describe JsonApiKit::Linkage::ToMany do
end
let(:record) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil),
resource.fields(guardian:),
type: "topics",
)
end
let(:records) { [record] }
- let(:next_page) { JsonApiKit::Pagination::Cursor.new([2]) }
- let(:previous_page) { JsonApiKit::Pagination::Cursor.new([1]) }
+ let(:next_page) { JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new([2]) }
+ let(:previous_page) { JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new([1]) }
let(:page) { JsonApiKit::Records::Page.new(JsonApiKit::Records.new(records), next_page) }
describe "#collapse" do
diff --git a/spec/lib/json_api_kit/linkage/to_one_spec.rb b/spec/lib/json_api_kit/linkage/to_one_spec.rb
index b11065cf30b..ba403a90f10 100644
--- a/spec/lib/json_api_kit/linkage/to_one_spec.rb
+++ b/spec/lib/json_api_kit/linkage/to_one_spec.rb
@@ -14,7 +14,7 @@ RSpec.describe JsonApiKit::Linkage::ToOne do
end
let(:record) do
JsonApiKit::Record.new(
- JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil),
resource.fields(guardian:),
type: "topics",
)
diff --git a/spec/lib/json_api_kit/pagination/scan_spec.rb b/spec/lib/json_api_kit/pagination/scan_spec.rb
deleted file mode 100644
index 2acc8b913e0..00000000000
--- a/spec/lib/json_api_kit/pagination/scan_spec.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-# 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/record_spec.rb b/spec/lib/json_api_kit/record_spec.rb
index 5684370a3cf..679a9ccdaa7 100644
--- a/spec/lib/json_api_kit/record_spec.rb
+++ b/spec/lib/json_api_kit/record_spec.rb
@@ -23,10 +23,10 @@ RSpec.describe JsonApiKit::Record do
attribute :username
end
end
- let(:row) { JsonApiKit::Pagination::Row.new(record: topic, segment: nil) }
+ let(:row) { JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil) }
let(:author_record) do
described_class.new(
- JsonApiKit::Pagination::Row.new(record: author, segment: nil),
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: author, segment: nil),
users_resource.fields(guardian:),
type: "users",
)
diff --git a/spec/lib/json_api_kit/request/contract/collection_spec.rb b/spec/lib/json_api_kit/request/contract/collection_spec.rb
index 267d1426243..a15160fa294 100644
--- a/spec/lib/json_api_kit/request/contract/collection_spec.rb
+++ b/spec/lib/json_api_kit/request/contract/collection_spec.rb
@@ -5,7 +5,11 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
let(:params) { {} }
let(:glossary) { JsonApiKit::Glossary.kit }
- let(:cursor) { JsonApiKit::Pagination::Cursor.new([resource.order({}).digest, 0, 12]).to_s }
+ let(:cursor) do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
+ [resource.order({}).digest, 0, 12],
+ ).to_s
+ end
let(:related) do
Class.new(JsonApiKit::Resource) do
model User
@@ -14,18 +18,28 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
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
+ 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
+ .new(guardian: Guardian.new)
+ end
+ let(:unbacked_resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ adapter JsonApiKit::Adapter
+ type :examples
+ end
+ .new(guardian: Guardian.new)
end
describe ".for" do
@@ -59,7 +73,7 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
context "when a parameter is unknown" do
let(:params) { { sorts: { created_at: :asc } } }
- it "adds an error on the parameter" do
+ it "adds an error on the parameter", :aggregate_failures do
expect(contract).to be_invalid
expect(contract.errors).to include(:sorts)
end
@@ -68,7 +82,7 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
context "when a page parameter is unknown" do
let(:params) { { page: { sise: 2 } } }
- it "adds an error under the parameter it came in" do
+ it "adds an error for the nested parameter", :aggregate_failures do
expect(contract).to be_invalid
expect(contract.errors).to include(:"page.sise")
end
@@ -103,7 +117,7 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
context "when a cursor comes with the sort" do
let(:params) { { sort: { title: :asc }, page: { after: cursor } } }
- it "checks the cursor against that sort" do
+ it "checks the cursor against that sort", :aggregate_failures do
expect(contract).to be_invalid
expect(contract.errors).to be_of_kind(:"page.after", :unreadable_cursor)
end
@@ -213,6 +227,15 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
it { is_expected.to validate_presence_of(:anchor) }
end
+
+ context "when the adapter has no anchor implementation" do
+ let(:resource) { unbacked_resource }
+ let(:params) { { page: { anchor: { unknown: 12 } } } }
+
+ it "reports the undeclared anchor" do
+ expect(contract.errors).to be_of_kind(:"page.anchor", :no_such_name)
+ end
+ end
end
describe "Pagination" do
@@ -220,10 +243,14 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
let(:params) { { page: {} } }
let(:cursor_not_matching_segment) do
- JsonApiKit::Pagination::Cursor.new([resource.order({}).digest, 7, 12]).to_s
+ JsonApiKit::Adapters::ActiveRecord::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
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new(
+ [resource.order({}).digest, 0],
+ ).to_s
end
before { contract.valid? }
@@ -267,7 +294,7 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
context "when the page is not a valid object" do
let(:params) { { page: "big" } }
- it { expect(contract).not_to be_valid }
+ it { expect(contract).to be_invalid }
end
context "when page[after] is present" do
@@ -281,6 +308,16 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
it { is_expected.to validate_absence_of(:after) }
end
+
+ context "when the adapter has no cursor implementation" do
+ let(:resource) { unbacked_resource }
+ let(:cursor) { JsonApiKit::Adapters::ActiveRecord::Pagination::Cursor.new([12]).to_s }
+ let(:params) { { page: { after: cursor } } }
+
+ it "reports the unsupported cursor" do
+ expect(contract.errors).to be_of_kind(:"page.after", :unreadable_cursor)
+ end
+ end
end
describe "Anchor window" do
diff --git a/spec/lib/json_api_kit/request_spec.rb b/spec/lib/json_api_kit/request_spec.rb
index 825b77bd270..eb45cae983d 100644
--- a/spec/lib/json_api_kit/request_spec.rb
+++ b/spec/lib/json_api_kit/request_spec.rb
@@ -8,28 +8,6 @@ RSpec.describe JsonApiKit::Request do
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) do
- described_class::Individual.new(params, guardian:, edition: JsonApiKit::Edition.current)
- end
-
- 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])) }
@@ -165,42 +143,10 @@ RSpec.describe JsonApiKit::Request do
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 } } }
+ let(:params) { { page: { size: 2, after: "opaque-cursor" } } }
- 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
+ it "preserves the pagination parameters for the adapter" do
+ expect(request.page).to eq(size: 2, after: "opaque-cursor")
end
end
diff --git a/spec/lib/json_api_kit/resource_spec.rb b/spec/lib/json_api_kit/resource_spec.rb
index 0cc90bd100e..a67df8027cd 100644
--- a/spec/lib/json_api_kit/resource_spec.rb
+++ b/spec/lib/json_api_kit/resource_spec.rb
@@ -305,7 +305,7 @@ RSpec.describe JsonApiKit::Resource do
sort :created_at
default_sort created_at: :sideways
end
- }.to raise_error(ArgumentError, /unknown direction: sideways/)
+ }.to raise_error(ArgumentError, /Unknown sort direction: :sideways/)
end
end
end
@@ -354,7 +354,7 @@ RSpec.describe JsonApiKit::Resource do
let(:historical_ordering) { { created_at: :sideways } }
it "rejects the ordering" do
- expect { ordering }.to raise_error(ArgumentError, /unknown direction: sideways/)
+ expect { ordering }.to raise_error(ArgumentError, /Unknown sort direction: :sideways/)
end
end
end
@@ -684,13 +684,18 @@ RSpec.describe JsonApiKit::Resource do
end
describe ".all" do
- before { allow(JsonApiKit::Query::Collection).to receive(:new) }
+ let(:instance) { topic_resource.new(guardian:) }
+ let(:adapter) { instance.adapter }
+
+ before do
+ allow(topic_resource).to receive(:new).and_return(instance)
+ allow(adapter).to receive(:all)
+ end
it "builds 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(
- an_instance_of(topic_resource),
+ expect(adapter).to have_received(:all).with(
an_object_having_attributes(ordering: { "created_at" => :asc }, guardian:),
scoped_to: nil,
)
@@ -701,7 +706,7 @@ RSpec.describe JsonApiKit::Resource do
fab!(:second_topic) { Fabricate(:topic, created_at: Time.utc(2026, 8, 2)) }
before do
- allow(JsonApiKit::Query::Collection).to receive(:new).and_call_original
+ allow(topic_resource).to receive(:new).and_call_original
topic_resource.default_sort created_at: :asc
end
@@ -714,14 +719,19 @@ RSpec.describe JsonApiKit::Resource do
end
describe ".find" do
- before { allow(JsonApiKit::Query::Individual).to receive(:new) }
+ let(:instance) { topic_resource.new(guardian:) }
+ let(:adapter) { instance.adapter }
+
+ before do
+ allow(topic_resource).to receive(:new).and_return(instance)
+ allow(adapter).to receive(:find)
+ end
it "resolves the default ordering before constructing the request" do
topic_resource.find(12, guardian:)
- expect(JsonApiKit::Query::Individual).to have_received(:new).with(
- an_instance_of(topic_resource),
- an_object_having_attributes(ordering: { "ran_at" => :desc }, guardian:),
+ expect(adapter).to have_received(:find).with(
+ an_object_having_attributes(id: 12, ordering: { "ran_at" => :desc }, guardian:),
)
end
end
diff --git a/spec/lib/json_api_kit/sideload_spec.rb b/spec/lib/json_api_kit/sideload_spec.rb
index a47d032c75c..feb88ec9798 100644
--- a/spec/lib/json_api_kit/sideload_spec.rb
+++ b/spec/lib/json_api_kit/sideload_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Sideload do
- subject(:sideload) { described_class.new(relationship, paths:, rows:, request:, schema:) }
+ subject(:sideload) { described_class.new(relationship, paths:, rows:, request:, owner_resource:) }
fab!(:author, :user)
fab!(:topic) { Fabricate(:topic, user: author, title: "A topic read with its author") }
@@ -18,7 +18,11 @@ RSpec.describe JsonApiKit::Sideload do
end
let(:paths) { JsonApiKit::Paths.new([]) }
let(:records) { [topic] }
- let(:rows) { records.map { JsonApiKit::Pagination::Row.new(record: it, segment: nil) } }
+ let(:rows) do
+ records.map do
+ JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: it, segment: nil)
+ end
+ end
let(:params) { {} }
let(:request) do
JsonApiKit::Request::Collection.new(
@@ -27,7 +31,14 @@ RSpec.describe JsonApiKit::Sideload do
edition: JsonApiKit::Edition.current,
)
end
- let(:schema) { JsonApiKit::Schema.new(Topic) }
+ let(:owner_resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ .new(guardian: request.guardian, edition: request.edition)
+ end
describe "#linkage_for" do
subject(:linkage) { sideload.linkage_for(rows.first) }
@@ -59,20 +70,6 @@ RSpec.describe JsonApiKit::Sideload do
end
end
- context "when a path goes 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: %w[username] } } }
diff --git a/spec/lib/json_api_kit/sideloads_spec.rb b/spec/lib/json_api_kit/sideloads_spec.rb
index 966d1060f4a..10cf4c4010e 100644
--- a/spec/lib/json_api_kit/sideloads_spec.rb
+++ b/spec/lib/json_api_kit/sideloads_spec.rb
@@ -1,7 +1,9 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Sideloads do
- subject(:sideloads) { described_class.for(relationships, paths:, rows:, request:, schema:) }
+ subject(:sideloads) do
+ described_class.for(relationships, paths:, rows:, request:, resource: owner_resource)
+ end
fab!(:author, :user)
fab!(:category) { Fabricate(:category, name: "Where the topic sits") }
@@ -38,7 +40,9 @@ RSpec.describe JsonApiKit::Sideloads do
]
end
let(:paths) { JsonApiKit::Paths.new(nil) }
- let(:rows) { [JsonApiKit::Pagination::Row.new(record: topic, segment: nil)] }
+ let(:rows) do
+ [JsonApiKit::Adapters::ActiveRecord::Pagination::Row.new(record: topic, segment: nil)]
+ end
let(:request) do
JsonApiKit::Request::Collection.new(
{},
@@ -46,7 +50,14 @@ RSpec.describe JsonApiKit::Sideloads do
edition: JsonApiKit::Edition.current,
)
end
- let(:schema) { JsonApiKit::Schema.new(Topic) }
+ let(:owner_resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ .new(guardian: request.guardian, edition: request.edition)
+ end
describe "#linkage_for" do
subject(:linkage) { sideloads.linkage_for(rows.first) }
diff --git a/spec/lib/json_api_kit/version_change/default_sorts_spec.rb b/spec/lib/json_api_kit/version_change/default_sorts_spec.rb
index 7678a25058a..c30c818a571 100644
--- a/spec/lib/json_api_kit/version_change/default_sorts_spec.rb
+++ b/spec/lib/json_api_kit/version_change/default_sorts_spec.rb
@@ -83,7 +83,10 @@ RSpec.describe JsonApiKit::VersionChange do
end
it "rejects the declaration" do
- expect { declare_default }.to raise_error(ArgumentError, /unknown direction: sideways/)
+ expect { declare_default }.to raise_error(
+ ArgumentError,
+ /Unknown sort direction: :sideways/,
+ )
end
end
end
diff --git a/spec/support/matchers/json_api_kit/have_relationship.rb b/spec/support/matchers/json_api_kit/have_relationship.rb
index 22ab87c8f6b..305d0f95397 100644
--- a/spec/support/matchers/json_api_kit/have_relationship.rb
+++ b/spec/support/matchers/json_api_kit/have_relationship.rb
@@ -45,7 +45,7 @@ module JsonApiKitMatchers
def association_table
@association_table ||= resource.schema.table_of(name.to_sym)
- rescue JsonApiKit::Schema::MissingAssociation => error
+ rescue JsonApiKit::Adapters::ActiveRecord::Schema::MissingAssociation => error
@missing = error.message
nil
end
diff --git a/spec/support/shared_examples/json_api_kit/resource_adapter.rb b/spec/support/shared_examples/json_api_kit/resource_adapter.rb
new file mode 100644
index 00000000000..6d3750a099d
--- /dev/null
+++ b/spec/support/shared_examples/json_api_kit/resource_adapter.rb
@@ -0,0 +1,111 @@
+# frozen_string_literal: true
+
+RSpec.shared_examples "a resource adapter" do
+ let(:record) { available_records.last }
+ let(:id) { record.id.to_s }
+ let(:parameters) { { sort: {} } }
+ let(:collection_request) do
+ JsonApiKit::Request::Collection.new(
+ parameters,
+ guardian: resource.guardian,
+ edition: resource.edition,
+ )
+ end
+ let(:individual_request) do
+ JsonApiKit::Request::Individual.new(
+ parameters.merge(id:),
+ guardian: resource.guardian,
+ edition: resource.edition,
+ )
+ end
+ let(:filter_value) { record.public_send(filter_name) }
+
+ describe "#all" do
+ subject(:loaded_records) { adapter.all(collection_request, scoped_to:).records.map(&:record) }
+
+ let(:scoped_to) { nil }
+
+ it "returns the available records" do
+ expect(loaded_records).to contain_exactly(*available_records)
+ end
+
+ context "when the collection is restricted" do
+ let(:scoped_to) { restricted_scope }
+
+ it "returns only the records in that scope" do
+ expect(loaded_records).to contain_exactly(record)
+ end
+ end
+
+ context "when the collection is empty" do
+ let(:scoped_to) { empty_scope }
+
+ it "returns no records" do
+ expect(loaded_records).to be_empty
+ end
+ end
+
+ context "when the request supplies a filter" do
+ let(:parameters) { super().merge(filter: { filter_name => filter_value }) }
+
+ it "returns only the matching records" do
+ expect(loaded_records).to contain_exactly(record)
+ end
+ end
+ end
+
+ describe "#find" do
+ subject(:query) { adapter.find(individual_request) }
+
+ it "returns the identified record" do
+ expect(query.record).to have_attributes(id:, type: resource.type, record:)
+ end
+
+ context "when the record does not exist" do
+ let(:id) { missing_id }
+
+ it "raises a missing record error" do
+ expect { query.record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+ end
+
+ describe "#record_for" do
+ subject(:found_record) { adapter.record_for(id) }
+
+ it "returns the underlying record" do
+ expect(found_record).to eq(record)
+ end
+
+ context "when the record does not exist" do
+ let(:id) { missing_id }
+
+ it "raises a missing record error" do
+ expect { found_record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+ end
+
+ describe "#filter" do
+ subject(:matching_records) do
+ adapter
+ .all(collection_request, scoped_to: adapter.filter(scope, filter_name, filter_value))
+ .records
+ .map(&:record)
+ end
+
+ it "restricts the scope to matching records" do
+ expect(matching_records).to contain_exactly(record)
+ end
+ end
+
+ describe "#collection?" do
+ it "recognizes a collection of supplied records" do
+ expect(adapter).to be_a_collection(available_records)
+ end
+
+ it "distinguishes an individual record" do
+ expect(adapter).not_to be_a_collection(record)
+ end
+ end
+end