Skip to content

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

DEV: Complete JSON:API pagination for query groups

Loïc Guitautc9d334e8b2ef
diff --git a/app/controllers/api/groups_controller.rb b/app/controllers/api/groups_controller.rb
new file mode 100644
index 00000000000..55837735f42
--- /dev/null
+++ b/app/controllers/api/groups_controller.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module Api
+ class GroupsController < JsonApiKit::BaseController
+ before_action :ensure_admin
+
+ resource :groups
+ end
+end
diff --git a/app/controllers/json_api_kit/base_controller.rb b/app/controllers/json_api_kit/base_controller.rb
index e3a7348e2dd..3d7e49c3722 100644
--- a/app/controllers/json_api_kit/base_controller.rb
+++ b/app/controllers/json_api_kit/base_controller.rb
@@ -1,17 +1,7 @@
# frozen_string_literal: true
module JsonApiKit
- class BaseController < ::ApplicationController
- skip_before_action :check_xhr,
- :redirect_to_login_if_required,
- :verify_authenticity_token,
- raise: false
-
- # Order matters here
- include Rendering
- include Negotiating
- include Versioning
- include Serving
+ class BaseController < EndpointController
include Fetching
include RequestInput
end
diff --git a/app/controllers/json_api_kit/base_controller/fetching.rb b/app/controllers/json_api_kit/base_controller/fetching.rb
index 48c7d1cf0af..f4c857abde8 100644
--- a/app/controllers/json_api_kit/base_controller/fetching.rb
+++ b/app/controllers/json_api_kit/base_controller/fetching.rb
@@ -5,8 +5,6 @@ module JsonApiKit
module Fetching
extend ActiveSupport::Concern
- ROOT = "/api"
-
def index
render_document(Document::Collection.for(request.query_parameters, resource:, client:))
end
@@ -16,18 +14,6 @@ module JsonApiKit
Document::Individual.for(params[:id], request.query_parameters, resource:, client:),
)
end
-
- private
-
- def client = Client.new(guardian:, edition:, urls:)
-
- def urls
- Urls.new(
- base: "#{request.base_url}#{ROOT}",
- current: "#{request.base_url}#{request.path}",
- parameters: request.query_parameters,
- )
- end
end
end
end
diff --git a/app/controllers/json_api_kit/base_controller/request_input.rb b/app/controllers/json_api_kit/base_controller/request_input.rb
index 2757bc53bef..8fd3606b56d 100644
--- a/app/controllers/json_api_kit/base_controller/request_input.rb
+++ b/app/controllers/json_api_kit/base_controller/request_input.rb
@@ -11,6 +11,17 @@ module JsonApiKit
def service_params = { params: request_body.parameters, guardian: }
+ def render_document(value, **options)
+ super(
+ Document.from(value) { { resource: request_resource, input: request_query, client: } },
+ **options,
+ )
+ end
+
+ def render_validation_errors(errors)
+ render_document(Document::Errors.new(*request_body.validation_errors(errors)))
+ end
+
def request_inputs
@request_inputs ||=
Request::Inputs.new(
diff --git a/app/controllers/json_api_kit/endpoint_controller.rb b/app/controllers/json_api_kit/endpoint_controller.rb
new file mode 100644
index 00000000000..6255e32b140
--- /dev/null
+++ b/app/controllers/json_api_kit/endpoint_controller.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class EndpointController < ::ApplicationController
+ skip_before_action :check_xhr,
+ :redirect_to_login_if_required,
+ :verify_authenticity_token,
+ raise: false
+
+ # Order matters here
+ include Rendering
+ include Negotiating
+ include Versioning
+ include Serving
+ include ClientContext
+ end
+end
diff --git a/app/controllers/json_api_kit/endpoint_controller/client_context.rb b/app/controllers/json_api_kit/endpoint_controller/client_context.rb
new file mode 100644
index 00000000000..7b1dfa4e524
--- /dev/null
+++ b/app/controllers/json_api_kit/endpoint_controller/client_context.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class EndpointController
+ module ClientContext
+ ROOT = "/api"
+
+ private
+
+ def client = Client.new(guardian:, edition:, urls:)
+
+ def urls
+ Urls.new(
+ base: "#{request.base_url}#{ROOT}",
+ current: "#{request.base_url}#{request.path}",
+ parameters: request.query_parameters,
+ )
+ end
+ end
+ end
+end
diff --git a/app/controllers/json_api_kit/base_controller/negotiating.rb b/app/controllers/json_api_kit/endpoint_controller/negotiating.rb
similarity index 98%
rename from app/controllers/json_api_kit/base_controller/negotiating.rb
rename to app/controllers/json_api_kit/endpoint_controller/negotiating.rb
index 957ce4d302d..500507a69db 100644
--- a/app/controllers/json_api_kit/base_controller/negotiating.rb
+++ b/app/controllers/json_api_kit/endpoint_controller/negotiating.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module JsonApiKit
- class BaseController
+ class EndpointController
module Negotiating
extend ActiveSupport::Concern
diff --git a/app/controllers/json_api_kit/base_controller/rendering.rb b/app/controllers/json_api_kit/endpoint_controller/rendering.rb
similarity index 77%
rename from app/controllers/json_api_kit/base_controller/rendering.rb
rename to app/controllers/json_api_kit/endpoint_controller/rendering.rb
index d250b262134..8cb7a0c4a70 100644
--- a/app/controllers/json_api_kit/base_controller/rendering.rb
+++ b/app/controllers/json_api_kit/endpoint_controller/rendering.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module JsonApiKit
- class BaseController
+ class EndpointController
module Rendering
extend ActiveSupport::Concern
@@ -27,9 +27,7 @@ module JsonApiKit
def set_json_format = request.format = :json
- def render_document(value, **options)
- document =
- Document.from(value) { { resource: request_resource, input: request_query, client: } }
+ def render_document(document, **options)
options = { status: document.status, content_type: Pagination::Profile::MEDIA_TYPE }.merge(
options,
)
@@ -37,10 +35,6 @@ module JsonApiKit
render json: document.to_h, **options
end
- def render_validation_errors(errors)
- render_document(Document::Errors.new(*request_body.validation_errors(errors)))
- end
-
def render_server_error(error)
Discourse.warn_exception(error, message: "JSON:API request failed")
render_document(Document::Errors.new(InternalServerError.new))
diff --git a/app/controllers/json_api_kit/base_controller/serving.rb b/app/controllers/json_api_kit/endpoint_controller/serving.rb
similarity index 95%
rename from app/controllers/json_api_kit/base_controller/serving.rb
rename to app/controllers/json_api_kit/endpoint_controller/serving.rb
index 8539c437040..5093309d773 100644
--- a/app/controllers/json_api_kit/base_controller/serving.rb
+++ b/app/controllers/json_api_kit/endpoint_controller/serving.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module JsonApiKit
- class BaseController
+ class EndpointController
module Serving
extend ActiveSupport::Concern
diff --git a/app/controllers/json_api_kit/base_controller/versioning.rb b/app/controllers/json_api_kit/endpoint_controller/versioning.rb
similarity index 95%
rename from app/controllers/json_api_kit/base_controller/versioning.rb
rename to app/controllers/json_api_kit/endpoint_controller/versioning.rb
index e87ba289ea0..ff37e18d129 100644
--- a/app/controllers/json_api_kit/base_controller/versioning.rb
+++ b/app/controllers/json_api_kit/endpoint_controller/versioning.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module JsonApiKit
- class BaseController
+ class EndpointController
module Versioning
extend ActiveSupport::Concern
diff --git a/app/controllers/json_api_kit/related_resources_controller.rb b/app/controllers/json_api_kit/related_resources_controller.rb
new file mode 100644
index 00000000000..803bdf4e9a2
--- /dev/null
+++ b/app/controllers/json_api_kit/related_resources_controller.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class RelatedResourcesController < EndpointController
+ include RelationshipReading
+
+ def index = render_relationship(Document::Collection)
+ end
+end
diff --git a/app/controllers/json_api_kit/relationship_reading.rb b/app/controllers/json_api_kit/relationship_reading.rb
new file mode 100644
index 00000000000..5cb63635a6b
--- /dev/null
+++ b/app/controllers/json_api_kit/relationship_reading.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module RelationshipReading
+ private
+
+ def render_relationship(document_class)
+ render_document(
+ document_class.for(
+ request.query_parameters,
+ resource: relationship.resource,
+ client:,
+ scoped_to: relationship.scope,
+ ),
+ )
+ end
+
+ def relationship
+ @relationship ||= Relationship.new(params[:id], relationship_name, resource: owner_resource)
+ end
+
+ def relationship_name = params[:relationship].tr("-", "_")
+
+ def owner_resource = resource.new(guardian:, edition:)
+ end
+end
diff --git a/app/controllers/json_api_kit/relationships_controller.rb b/app/controllers/json_api_kit/relationships_controller.rb
new file mode 100644
index 00000000000..6723f86a6d0
--- /dev/null
+++ b/app/controllers/json_api_kit/relationships_controller.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class RelationshipsController < EndpointController
+ include RelationshipReading
+
+ def show = render_relationship(Document::Relationship)
+ end
+end
diff --git a/config/routes.rb b/config/routes.rb
index 62d555c8b25..5bc85dbdc72 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -2104,6 +2104,10 @@ Discourse::Application.routes.draw do
get "/test_postgres_readonly" => "test_requests#test_postgres_readonly"
end
+ namespace :api do
+ resources :groups, only: :show
+ end
+
# This catch-all route should always be last
get "*url", to: "permalinks#show", constraints: PermalinkConstraint.new
end
diff --git a/lib/json_api_kit/document/collection.rb b/lib/json_api_kit/document/collection.rb
index ff3c9c0bf48..10f32aae74a 100644
--- a/lib/json_api_kit/document/collection.rb
+++ b/lib/json_api_kit/document/collection.rb
@@ -20,9 +20,11 @@ module JsonApiKit
def primary_records = query.records
def data
- contents.primary.map do
- ResourceObject.new(it, client:, fieldsets:, meta: page_meta(it)).to_h
- end
+ contents.primary.map { representation(it, meta: page_meta(it)).to_h }
+ end
+
+ def representation(record, meta:)
+ ResourceObject.new(record, client:, fieldsets:, meta:)
end
def page_meta(record)
diff --git a/lib/json_api_kit/document/relationship.rb b/lib/json_api_kit/document/relationship.rb
new file mode 100644
index 00000000000..6def70d57da
--- /dev/null
+++ b/lib/json_api_kit/document/relationship.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class Relationship < Collection
+ def self.input_class = Request::Input::Relationship
+
+ private
+
+ def representation(record, meta:)
+ ResourceIdentifier.new(record, glossary: client.glossary, meta:)
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/document/relationship_object.rb b/lib/json_api_kit/document/relationship_object.rb
index 205e6877e28..c9384c4bcc3 100644
--- a/lib/json_api_kit/document/relationship_object.rb
+++ b/lib/json_api_kit/document/relationship_object.rb
@@ -5,7 +5,6 @@ module JsonApiKit
class RelationshipObject
delegate :pages, to: :linkage, private: true
delegate :urls, :glossary, to: :client, private: true
- delegate :member_type, to: :glossary, private: true
def initialize(linkage, client:, owner:, name:)
@linkage = linkage
@@ -23,7 +22,7 @@ module JsonApiKit
def data = linkage.collapse { identifier(it) }
def identifier(record)
- { type: member_type(record.type), id: record.id }
+ ResourceIdentifier.new(record, glossary:).to_h
end
def links = { self: relationship_url.to_s, related: related_url.to_s }.merge(page_links)
diff --git a/lib/json_api_kit/document/resource_identifier.rb b/lib/json_api_kit/document/resource_identifier.rb
new file mode 100644
index 00000000000..a98610b35f8
--- /dev/null
+++ b/lib/json_api_kit/document/resource_identifier.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Document
+ class ResourceIdentifier
+ def initialize(record, glossary:, meta: {})
+ @record = record
+ @glossary = glossary
+ @meta = meta
+ end
+
+ def to_h = { type: glossary.member_type(record.type), id: record.id, meta: }.compact_blank
+
+ private
+
+ attr_reader :record, :glossary, :meta
+ end
+ end
+end
diff --git a/lib/json_api_kit/relationship.rb b/lib/json_api_kit/relationship.rb
new file mode 100644
index 00000000000..4e96f71ea2e
--- /dev/null
+++ b/lib/json_api_kit/relationship.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Relationship
+ def initialize(owner_id, name, resource:)
+ @owner_id = owner_id
+ @name = name
+ @owner_resource = resource
+ end
+
+ delegate :resource, to: :declaration
+
+ def scope = owner_resource.related_scope(declaration.name, owner_id:)
+
+ private
+
+ attr_reader :owner_id, :name, :owner_resource
+
+ delegate :guardian, to: :owner_resource, private: true
+
+ def declaration
+ @declaration ||=
+ owner_resource
+ .relationships
+ .fetch(name) { raise NotFound.new }
+ .tap { |relationship| raise NotFound.new unless relationship.readable_by?(guardian) }
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract/relationship.rb b/lib/json_api_kit/request/contract/relationship.rb
new file mode 100644
index 00000000000..cb692dae814
--- /dev/null
+++ b/lib/json_api_kit/request/contract/relationship.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Contract
+ class Relationship < Contract
+ include Fields
+ include Sorting
+ include Filtering
+ include Paging
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/input/relationship.rb b/lib/json_api_kit/request/input/relationship.rb
new file mode 100644
index 00000000000..3364fd7976e
--- /dev/null
+++ b/lib/json_api_kit/request/input/relationship.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Input
+ class Relationship < Collection
+ private
+
+ def contract_class = Contract::Relationship
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/resource/current_values.rb b/lib/json_api_kit/resource/current_values.rb
index e834609eb31..c47105f4660 100644
--- a/lib/json_api_kit/resource/current_values.rb
+++ b/lib/json_api_kit/resource/current_values.rb
@@ -17,11 +17,7 @@ module JsonApiKit
attr_reader :resource, :id, :values
- delegate :guardian, :schema, to: :resource
-
- def record
- @record ||= resource.scope_for(guardian).find_by(schema.primary_key => id) or raise NotFound
- end
+ def record = @record ||= resource.record_for(id)
def attribute_value(name)
resource.attribute_value(name, record:)
diff --git a/lib/json_api_kit/resource/query_interface.rb b/lib/json_api_kit/resource/query_interface.rb
index 6598590b3af..26b40a9992b 100644
--- a/lib/json_api_kit/resource/query_interface.rb
+++ b/lib/json_api_kit/resource/query_interface.rb
@@ -56,6 +56,14 @@ 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/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_related_resources_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_related_resources_controller.rb
new file mode 100644
index 00000000000..6edc6763d91
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_related_resources_controller.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class QueryRelatedResourcesController < JsonApiKit::RelatedResourcesController
+ requires_plugin PLUGIN_NAME
+
+ before_action :ensure_admin
+
+ resource :queries
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_relationships_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_relationships_controller.rb
new file mode 100644
index 00000000000..2261adcb3dd
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_relationships_controller.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class QueryRelationshipsController < JsonApiKit::RelationshipsController
+ requires_plugin PLUGIN_NAME
+
+ before_action :ensure_admin
+
+ resource :queries
+ end
+end
diff --git a/plugins/discourse-data-explorer/config/routes.rb b/plugins/discourse-data-explorer/config/routes.rb
index 634b22a1dcc..422766e1b2d 100644
--- a/plugins/discourse-data-explorer/config/routes.rb
+++ b/plugins/discourse-data-explorer/config/routes.rb
@@ -22,6 +22,16 @@ end
Discourse::Application.routes.draw do
get "/api/data-explorer/queries" => "discourse_data_explorer/queries#index"
get "/api/data-explorer/queries/:id" => "discourse_data_explorer/queries#show"
+ get "/api/data-explorer/queries/:id/relationships/groups" =>
+ "discourse_data_explorer/query_relationships#show",
+ :defaults => {
+ relationship: "groups",
+ }
+ get "/api/data-explorer/queries/:id/groups" =>
+ "discourse_data_explorer/query_related_resources#index",
+ :defaults => {
+ relationship: "groups",
+ }
get "/g/:group_name/reports" => "discourse_data_explorer/query#group_reports_index"
get "/g/:group_name/reports/:id" => "discourse_data_explorer/query#group_reports_show"
diff --git a/plugins/discourse-data-explorer/spec/requests/api/query_relationships_spec.rb b/plugins/discourse-data-explorer/spec/requests/api/query_relationships_spec.rb
new file mode 100644
index 00000000000..8b18dc92b30
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/requests/api/query_relationships_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+RSpec.describe "JSON:API query relationships", type: :request do
+ fab!(:admin)
+ fab!(:groups) { Fabricate.times(61, :group) }
+ fab!(:unrelated_group, :group)
+
+ let!(:query) { Fabricate(:query, hidden:) }
+ let(:hidden) { false }
+ let(:user) { admin }
+ let(:headers) { { "HTTP_API_VERSION" => JsonApiKit::Timeline.current.to_s } }
+ let(:query_path) { "/api/data-explorer/queries/#{query.id}" }
+ let(:first_page) { JSON.parse(response.body) }
+ let(:second_page) { JSON.parse(response.body) }
+ let(:third_page) { JSON.parse(response.body) }
+ let(:expected_ids) { groups.map(&:id).sort.map(&:to_s) }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ host! Discourse.current_hostname
+ sign_in(user)
+ query.groups = groups
+ end
+
+ describe "GET /relationships/groups" do
+ let(:relationship) { first_page.dig("data", "relationships", "groups") }
+ let(:first_page_ids) { relationship.fetch("data").map { it.fetch("id") } }
+ let(:second_page_ids) { second_page.fetch("data").map { it.fetch("id") } }
+ let(:third_page_ids) { third_page.fetch("data").map { it.fetch("id") } }
+
+ before { get(query_path, headers:, params: { include: "groups" }) }
+
+ it "continues the embedded group membership through every page", :aggregate_failures do
+ expect(first_page_ids.size).to eq(25)
+
+ get(relationship.dig("links", "next"), headers:)
+
+ expect(second_page_ids.size).to eq(25)
+
+ get(second_page.dig("links", "next"), headers:)
+
+ expect(first_page_ids + second_page_ids + third_page_ids).to eq(expected_ids)
+ expect(third_page.fetch("links")).to include("next" => nil)
+ end
+ end
+
+ describe "GET /groups" do
+ let(:group_data) do
+ groups
+ .sort_by(&:id)
+ .first(25)
+ .map do |group|
+ a_hash_including(
+ "type" => "groups",
+ "id" => group.id.to_s,
+ "attributes" => {
+ "name" => group.name,
+ },
+ )
+ end
+ end
+
+ before { get("#{query_path}/groups", headers:) }
+
+ it "returns the query's group resources" do
+ expect(first_page.fetch("data")).to match(group_data)
+ end
+
+ it "provides a working group self link" do
+ get(first_page.dig("data", 0, "links", "self"), headers:)
+
+ expect(JSON.parse(response.body).fetch("data")).to include(
+ "type" => "groups",
+ "id" => expected_ids.first,
+ )
+ end
+
+ context "when the query is hidden" do
+ let(:hidden) { true }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the query is a default query" do
+ let!(:query) do
+ DiscourseDataExplorer::Query
+ .find(-1)
+ .tap do |query|
+ query.hidden = hidden
+ query.save!
+ end
+ end
+
+ it "returns the query's group resources" do
+ expect(first_page.fetch("data")).to match(group_data)
+ end
+
+ context "when the query is hidden" do
+ let(:hidden) { true }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+ end
+
+ context "when the user is not an admin" do
+ fab!(:visitor, :user)
+
+ let(:user) { visitor }
+
+ it { expect(response).to have_http_status(:forbidden) }
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/endpoint_spec.rb b/spec/integration/json_api_kit/endpoint_spec.rb
index e68e7393e72..b8dfa898677 100644
--- a/spec/integration/json_api_kit/endpoint_spec.rb
+++ b/spec/integration/json_api_kit/endpoint_spec.rb
@@ -78,7 +78,7 @@ RSpec.describe "a JSON:API endpoint", type: :request do
it "reports a missing declaration" do
expect(Discourse).to have_received(:warn_exception) do |error, _|
- expect(error).to be_a(JsonApiKit::BaseController::Serving::MissingDeclaration)
+ expect(error).to be_a(JsonApiKit::EndpointController::Serving::MissingDeclaration)
expect(error.message).to match(/declare the resource it serves/)
end
end
diff --git a/spec/integration/json_api_kit/relationship_endpoints_spec.rb b/spec/integration/json_api_kit/relationship_endpoints_spec.rb
new file mode 100644
index 00000000000..ed8a2999453
--- /dev/null
+++ b/spec/integration/json_api_kit/relationship_endpoints_spec.rb
@@ -0,0 +1,214 @@
+# frozen_string_literal: true
+
+module JsonApiKitSpec
+ class EndpointUserResource < JsonApiKit::Resource
+ model User
+ type :users
+ attribute :username
+ end
+
+ class EndpointPostResource < JsonApiKit::Resource
+ model Post
+ type :posts
+ attribute :raw
+ scope { Post.where(deleted_at: nil) }
+ has_one :user, resource: EndpointUserResource
+ sort :post_number
+ default_sort post_number: :asc
+ page default: 2
+ end
+
+ class EndpointTopicResource < JsonApiKit::Resource
+ model Topic
+ type :topics
+ attribute :title
+ scope { Topic.where(deleted_at: nil) }
+ has_many :posts, resource: EndpointPostResource, readable: :is_admin?.to_proc
+ end
+
+ class TopicRelationshipsController < JsonApiKit::RelationshipsController
+ resource EndpointTopicResource
+ end
+
+ class TopicRelatedResourcesController < JsonApiKit::RelatedResourcesController
+ resource EndpointTopicResource
+ end
+end
+
+RSpec.describe "JSON:API relationship endpoints", type: :request do
+ fab!(:admin)
+ fab!(:topic)
+ fab!(:posts) { Fabricate.times(3, :post, topic:) }
+ fab!(:deleted_post) { Fabricate(:post, topic:, deleted_at: 1.day.ago) }
+ fab!(:unrelated_post, :post)
+
+ let(:user) { admin }
+ let(:owner_id) { topic.id }
+ let(:relationship_name) { "posts" }
+ let(:parameters) { {} }
+ let(:headers) { { "HTTP_API_VERSION" => JsonApiKit::Timeline.current.to_s } }
+ let(:body) { JSON.parse(response.body) }
+ let(:identifiers) { posts.first(2).map { { "type" => "posts", "id" => it.id.to_s } } }
+
+ before do
+ host! Discourse.current_hostname
+ sign_in(user)
+ Rails.application.routes.disable_clear_and_finalize = true
+ Rails.application.routes.draw do
+ get "/api/topics/:id/relationships/:relationship" =>
+ "json_api_kit_spec/topic_relationships#show"
+ get "/api/topics/:id/:relationship" => "json_api_kit_spec/topic_related_resources#index"
+ end
+ Rails.application.routes.disable_clear_and_finalize = false
+ end
+
+ after { Rails.application.reload_routes! }
+
+ describe "GET /show" do
+ let(:path) { "/api/topics/#{owner_id}/relationships/#{relationship_name}" }
+ let(:next_page) { JSON.parse(response.body) }
+
+ before { get(path, headers:, params: parameters) }
+
+ it "returns identifiers within the owner and related resource scopes" do
+ expect(body.fetch("data")).to eq(identifiers)
+ end
+
+ it "continues the relationship with the related resource's ordering" do
+ get(body.dig("links", "next"), headers:)
+
+ expect(next_page.fetch("data")).to eq([{ "type" => "posts", "id" => posts.last.id.to_s }])
+ end
+
+ context "when the requested page size exceeds the default" do
+ let(:parameters) { super().merge(page: { size: 3 }) }
+
+ it "returns the requested number of identifiers" do
+ expect(body.fetch("data").size).to eq(3)
+ end
+ end
+
+ context "when the request asks for item cursors" do
+ let(:parameters) { super().merge(page: { itemCursors: true }) }
+
+ it "includes a cursor with each resource identifier" do
+ expect(body.fetch("data")).to all(
+ include("meta" => { "page" => { "cursor" => a_kind_of(String) } }),
+ )
+ end
+ end
+
+ context "when the owner is outside its resource scope" do
+ fab!(:deleted_topic) { Fabricate(:topic, deleted_at: 1.day.ago) }
+
+ let(:owner_id) { deleted_topic.id }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the owner does not exist" do
+ let(:owner_id) { 0 }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the relationship is not declared" do
+ let(:relationship_name) { "title" }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the relationship is not readable" do
+ fab!(:visitor, :user)
+
+ let(:user) { visitor }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the relationship is empty" do
+ fab!(:empty_topic, :topic)
+
+ let(:owner_id) { empty_topic.id }
+
+ it "returns empty linkage", :aggregate_failures do
+ expect(response).to have_http_status(:ok)
+ expect(body.fetch("data")).to be_empty
+ end
+ end
+
+ context "when the request asks for included resources" do
+ let(:parameters) { super().merge(include: "user") }
+
+ it "rejects include as an unsupported parameter", :aggregate_failures do
+ expect(response).to have_http_status(:bad_request)
+ expect(body.fetch("errors").sole).to include(
+ "title" => "No such parameter",
+ "source" => {
+ "parameter" => "include",
+ },
+ )
+ end
+
+ context "when include is empty" do
+ let(:parameters) { super().merge(include: "") }
+
+ it { expect(response).to have_http_status(:bad_request) }
+ end
+ end
+ end
+
+ describe "GET /index" do
+ let(:path) { "/api/topics/#{owner_id}/#{relationship_name}" }
+ let(:data) do
+ posts
+ .first(2)
+ .map do |post|
+ a_hash_including(
+ "type" => "posts",
+ "id" => post.id.to_s,
+ "attributes" => {
+ "raw" => post.raw,
+ },
+ )
+ end
+ end
+
+ before { get(path, headers:, params: parameters) }
+
+ it "returns the related resource objects" do
+ expect(body.fetch("data")).to match(data)
+ end
+
+ context "when the request asks for included resources" do
+ let(:parameters) { super().merge(include: "user") }
+ let(:user_data) do
+ posts
+ .first(2)
+ .map(&:user)
+ .uniq
+ .map do |user|
+ a_hash_including(
+ "type" => "users",
+ "id" => user.id.to_s,
+ "attributes" => {
+ "username" => user.username,
+ },
+ )
+ end
+ end
+
+ it "returns the requested users" do
+ expect(body.fetch("included")).to contain_exactly(*user_data)
+ end
+ end
+
+ context "when the request uses the related resource's fieldset" do
+ let(:parameters) { super().merge(fields: { posts: "" }) }
+
+ it "omits unrequested attributes" do
+ expect(body.fetch("data")).to all(exclude("attributes"))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/resource/instance_spec.rb b/spec/lib/json_api_kit/resource/instance_spec.rb
index 18bfc26cd4e..9496ac97224 100644
--- a/spec/lib/json_api_kit/resource/instance_spec.rb
+++ b/spec/lib/json_api_kit/resource/instance_spec.rb
@@ -103,4 +103,61 @@ RSpec.describe JsonApiKit::Resource do
expect(ordering).to eq("created_at" => :desc)
end
end
+
+ describe "#record_for" do
+ subject(:record) { resource.record_for(id) }
+
+ fab!(:topic) { Fabricate(:topic, closed: false) }
+
+ let(:id) { topic.id }
+ let(:resource_class) { Class.new(super()) { scope { Topic.where(closed: false) } } }
+
+ it "returns the model record" do
+ expect(record).to eq(topic)
+ end
+
+ context "when the record is outside the resource scope" do
+ fab!(:closed_topic) { Fabricate(:topic, closed: true) }
+
+ let(:id) { closed_topic.id }
+
+ it "refuses the lookup" do
+ expect { record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+
+ context "when the record does not exist" do
+ let(:id) { 0 }
+
+ it "refuses the lookup" do
+ expect { record }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+ end
+
+ describe "#related_scope" do
+ subject(:scope) { resource.related_scope(:posts, owner_id:) }
+
+ fab!(:topic) { Fabricate(:topic, closed: false) }
+ fab!(:post) { Fabricate(:post, topic:) }
+ fab!(:unrelated_post, :post)
+
+ let(:changes) { [] }
+ let(:owner_id) { topic.id }
+ let(:resource_class) { Class.new(super()) { scope { Topic.where(closed: false) } } }
+
+ it "restricts the association to the owner" do
+ expect(scope).to contain_exactly(post)
+ end
+
+ context "when the owner is outside the resource scope" do
+ fab!(:closed_topic) { Fabricate(:topic, closed: true) }
+
+ let(:owner_id) { closed_topic.id }
+
+ it "refuses the lookup" do
+ expect { scope }.to raise_error(JsonApiKit::NotFound)
+ end
+ end
+ end
end
diff --git a/spec/requests/api/groups_controller_spec.rb b/spec/requests/api/groups_controller_spec.rb
new file mode 100644
index 00000000000..46061269cca
--- /dev/null
+++ b/spec/requests/api/groups_controller_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+RSpec.describe "JSON:API groups", type: :request do
+ fab!(:admin)
+ fab!(:group) { Fabricate(:group, visibility_level: Group.visibility_levels[:owners]) }
+
+ let(:user) { admin }
+ let(:id) { group.id }
+ let(:headers) { { "HTTP_API_VERSION" => JsonApiKit::Timeline.current.to_s } }
+
+ before do
+ sign_in(user)
+ get("/api/groups/#{id}", headers:)
+ end
+
+ describe "GET /show" do
+ it "returns the group to an admin" do
+ expect(JSON.parse(response.body).fetch("data")).to include(
+ "type" => "groups",
+ "id" => group.id.to_s,
+ "attributes" => {
+ "name" => group.name,
+ },
+ )
+ end
+
+ context "when the user is not an admin" do
+ fab!(:visitor, :user)
+
+ let(:user) { visitor }
+
+ it { expect(response).to have_http_status(:forbidden) }
+ end
+
+ context "when the group does not exist" do
+ let(:id) { Group.maximum(:id) + 1 }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+ end
+end