Skip to content

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

DEV: Serve the data explorer queries as JSON:API (#42859)

Loïc Guitaut61daba9e2a80
diff --git a/app/controllers/json_api_kit/base_controller.rb b/app/controllers/json_api_kit/base_controller.rb
index ea43f5af1b5..d7cdd6eff35 100644
--- a/app/controllers/json_api_kit/base_controller.rb
+++ b/app/controllers/json_api_kit/base_controller.rb
@@ -2,6 +2,8 @@
module JsonApiKit
class BaseController < ::ApplicationController
+ MissingDeclaration = Class.new(StandardError)
+
ROOT = "/api"
OTHER_PARAMETER = "Content-Type accepts the ext and profile parameters only."
NO_EXTENSION = "This API applies no extension."
@@ -13,18 +15,50 @@ module JsonApiKit
:verify_authenticity_token,
raise: false
+ class_attribute :declared_resource, instance_accessor: false
+
before_action :set_json_format
before_action :set_vary_header
before_action :negotiate
rescue_from(Discourse::InvalidAccess) { render_document(Document::Errors.new(Forbidden.new)) }
+ class << self
+ def resource(declaration)
+ self.declared_resource = ResourceLookup.resource(declaration, within: self)
+ end
+ end
+
def rescue_with_handler(*)
super || render_server_error(*)
end
+ def index
+ render_document(
+ Document::Collection.for(request.query_parameters, resource:, guardian:, urls:),
+ )
+ end
+
+ def show
+ render_document(
+ Document::Individual.for(
+ params[:id],
+ request.query_parameters,
+ resource:,
+ guardian:,
+ urls:,
+ ),
+ )
+ end
+
private
+ def resource
+ self.class.declared_resource or
+ raise MissingDeclaration,
+ "#{self.class}: declare the resource it serves with `resource :things`"
+ end
+
def urls
Urls.new(
base: "#{request.base_url}#{ROOT}",
diff --git a/app/resources/group_resource.rb b/app/resources/group_resource.rb
new file mode 100644
index 00000000000..e29cce15a70
--- /dev/null
+++ b/app/resources/group_resource.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class GroupResource < JsonApiKit::Resource
+ attribute :name
+end
diff --git a/app/resources/user_resource.rb b/app/resources/user_resource.rb
new file mode 100644
index 00000000000..958f62685ef
--- /dev/null
+++ b/app/resources/user_resource.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class UserResource < JsonApiKit::Resource
+ attribute :username
+end
diff --git a/lib/json_api_kit/document/relationship_object.rb b/lib/json_api_kit/document/relationship_object.rb
index 32f4c70b90e..0faaee7eaeb 100644
--- a/lib/json_api_kit/document/relationship_object.rb
+++ b/lib/json_api_kit/document/relationship_object.rb
@@ -22,9 +22,11 @@ module JsonApiKit
def links = { self: relationship_url.to_s, related: related_url.to_s }.merge(page_links)
- def relationship_url = urls.relationship(owner.type, owner.id, name)
+ def relationship_url = owner_url.relationship(name)
- def related_url = urls.related(owner.type, owner.id, name)
+ def related_url = owner_url.related(name)
+
+ def owner_url = @owner_url ||= urls.for(owner)
def page_links = PageLinks.new(relationship_url, pages).to_h
end
diff --git a/lib/json_api_kit/document/resource_object.rb b/lib/json_api_kit/document/resource_object.rb
index 8afcc931dd1..ef1f1379894 100644
--- a/lib/json_api_kit/document/resource_object.rb
+++ b/lib/json_api_kit/document/resource_object.rb
@@ -23,7 +23,7 @@ module JsonApiKit
end
end
- def links = { self: urls.record(type, id).to_s }
+ def links = { self: urls.for(record).to_s }
end
end
end
diff --git a/lib/json_api_kit/query.rb b/lib/json_api_kit/query.rb
index cccfb72e363..bcc5858ecfa 100644
--- a/lib/json_api_kit/query.rb
+++ b/lib/json_api_kit/query.rb
@@ -14,7 +14,7 @@ module JsonApiKit
@records ||=
Records.new(
rows.map do
- Record.new(it, fields, type: resource.type, relationships: sideloads.linkage_for(it))
+ Record.new(it, fields, type:, namespace:, relationships: sideloads.linkage_for(it))
end,
)
end
@@ -28,6 +28,7 @@ module JsonApiKit
attr_reader :resource, :request, :scoped_to
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:)
@@ -49,7 +50,7 @@ module JsonApiKit
def schema = @schema ||= resource.schema
- def fields = @fields ||= resource.fields(request.fields[resource.type], guardian:)
+ def fields = @fields ||= resource.fields(request.fields[type], guardian:)
def sideloads
@sideloads ||= Sideloads.for(relationships, paths:, rows:, request:, schema:)
diff --git a/lib/json_api_kit/record.rb b/lib/json_api_kit/record.rb
index 029265a87a2..d2a4b7323c5 100644
--- a/lib/json_api_kit/record.rb
+++ b/lib/json_api_kit/record.rb
@@ -6,12 +6,13 @@ module JsonApiKit
delegate :record, :cursor, to: :row
- attr_reader :type, :relationships
+ attr_reader :type, :namespace, :relationships
- def initialize(row, fields, type:, relationships: {})
+ def initialize(row, fields, type:, namespace: nil, relationships: {})
@row = row
@fields = fields
@type = type
+ @namespace = namespace
@relationships = relationships
end
@@ -22,7 +23,13 @@ module JsonApiKit
def attributes = fields.attributes.values_for(record)
def merge(other)
- self.class.new(row, fields, type:, relationships: other.relationships.merge(relationships))
+ self.class.new(
+ row,
+ fields,
+ type:,
+ namespace:,
+ relationships: other.relationships.merge(relationships),
+ )
end
def related_records = relationships.values.flat_map(&:records)
diff --git a/lib/json_api_kit/record_url.rb b/lib/json_api_kit/record_url.rb
new file mode 100644
index 00000000000..b27faf54bc5
--- /dev/null
+++ b/lib/json_api_kit/record_url.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class RecordUrl
+ def initialize(base, record)
+ @base = base
+ @record = record
+ end
+
+ def to_s = address
+
+ def relationship(name) = Url.new("#{address}/relationships/#{name}")
+
+ def related(name) = Url.new("#{address}/#{name}")
+
+ private
+
+ attr_reader :base, :record
+
+ def address = [base, record.namespace, record.type, record.id].compact.join("/")
+ end
+end
diff --git a/lib/json_api_kit/resource/fields.rb b/lib/json_api_kit/resource/fields.rb
index e0e7bf055ad..b9794db1eb9 100644
--- a/lib/json_api_kit/resource/fields.rb
+++ b/lib/json_api_kit/resource/fields.rb
@@ -27,9 +27,9 @@ module JsonApiKit
self.declared_attributes = declared_attributes + [Declarations::Attribute.new(...)]
end
- def has_one(...) = relate(Declarations::Relationship::ToOne.new(...))
+ def has_one(name, **options) = relate(Declarations::Relationship::ToOne, name, **options)
- def has_many(...) = relate(Declarations::Relationship::ToMany.new(...))
+ def has_many(name, **options) = relate(Declarations::Relationship::ToMany, name, **options)
def fields(names = nil, guardian:)
Declarations::Fields.for(
@@ -45,8 +45,16 @@ module JsonApiKit
def relationships = Declarations::Relationships.new(declared_relationships)
- def relate(relationship)
- self.declared_relationships = declared_relationships + [relationship]
+ def relate(kind, name, resource: nil, **options)
+ self.declared_relationships =
+ declared_relationships +
+ [
+ kind.new(
+ name,
+ resource: ResourceLookup.resource(resource || name, within: self),
+ **options,
+ ),
+ ]
end
end
end
diff --git a/lib/json_api_kit/resource/naming.rb b/lib/json_api_kit/resource/naming.rb
index d9508a15f95..8a4bc9d5bcc 100644
--- a/lib/json_api_kit/resource/naming.rb
+++ b/lib/json_api_kit/resource/naming.rb
@@ -13,9 +13,15 @@ module JsonApiKit
included do
class_attribute :declared_model,
:declared_type,
+ :declared_namespace,
instance_accessor: false,
instance_predicate: false
- private_class_method :declared_model, :declared_model=, :declared_type, :declared_type=
+ private_class_method :declared_model,
+ :declared_model=,
+ :declared_type,
+ :declared_type=,
+ :declared_namespace,
+ :declared_namespace=
end
class_methods do
@@ -32,6 +38,11 @@ module JsonApiKit
self.declared_type = declaration.to_s
end
+ def namespace(declaration = nil)
+ return declared_namespace unless declaration
+ self.declared_namespace = declaration.to_s
+ end
+
private
def resolved_model = @resolved_model ||= model_for(declared_model || name_parts[:path])
diff --git a/lib/json_api_kit/resource_lookup.rb b/lib/json_api_kit/resource_lookup.rb
new file mode 100644
index 00000000000..b305761d8aa
--- /dev/null
+++ b/lib/json_api_kit/resource_lookup.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class ResourceLookup
+ MissingResource = Class.new(StandardError)
+ UnsupportedResource = Class.new(StandardError)
+
+ def self.resource(...) = new(...).resource
+
+ private_class_method :new
+
+ def initialize(declaration, within:)
+ @declaration = declaration
+ @within = within
+ end
+
+ def resource
+ return resolved_class if resolved_class.ancestors.include?(Resource)
+ raise UnsupportedResource, "#{within}: #{resolved_class} is not a JSON:API resource"
+ end
+
+ private
+
+ attr_reader :declaration, :within
+
+ def resolved_class
+ @resolved_class ||=
+ if declaration.is_a?(Class)
+ declaration
+ else
+ candidates.filter_map(&:safe_constantize).first or raise MissingResource, no_resource
+ end
+ end
+
+ def candidates
+ @candidates ||= within.module_parents.map { it == Object ? basename : "#{it}::#{basename}" }
+ end
+
+ def basename = "#{declaration.to_s.singularize.camelize}Resource"
+
+ def no_resource
+ "#{within}: no resource is named #{declaration}, tried #{candidates.join(", ")}"
+ end
+ end
+end
diff --git a/lib/json_api_kit/urls.rb b/lib/json_api_kit/urls.rb
index 968a7c36b8f..58293f5b46b 100644
--- a/lib/json_api_kit/urls.rb
+++ b/lib/json_api_kit/urls.rb
@@ -10,11 +10,7 @@ module JsonApiKit
def current = Url.new(@current, parameters)
- def record(type, id) = Url.new("#{base}/#{type}/#{id}")
-
- def relationship(type, id, name) = Url.new("#{record(type, id)}/relationships/#{name}")
-
- def related(type, id, name) = Url.new("#{record(type, id)}/#{name}")
+ def for(record) = RecordUrl.new(base, record)
private
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/queries_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/queries_controller.rb
new file mode 100644
index 00000000000..73f2ad7417a
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/queries_controller.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class QueriesController < JsonApiKit::BaseController
+ requires_plugin PLUGIN_NAME
+
+ before_action :ensure_admin
+
+ resource :queries
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/resources/discourse_data_explorer/query_resource.rb b/plugins/discourse-data-explorer/app/resources/discourse_data_explorer/query_resource.rb
new file mode 100644
index 00000000000..55467f7fb53
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/resources/discourse_data_explorer/query_resource.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class QueryResource < JsonApiKit::Resource
+ namespace "data-explorer"
+
+ scope { Query.where(hidden: false) }
+
+ attribute :name
+ attribute :description
+ attribute :created_at
+ attribute :last_run_at
+ attribute :sql, readable: ->(guardian) { guardian.is_admin? }
+ attribute(:param_info) { it.params.uniq(&:identifier).map(&:to_hash) }
+ attribute(:is_default) { it.id.negative? }
+
+ has_one :user
+ has_many :groups
+
+ sort :name
+ sort :last_run_at
+ sort "user.username"
+ default_sort last_run_at: :desc
+
+ anchor :id
+ anchor :name
+ anchor :last_run_at
+
+ page default: 50
+
+ filter :search do |scope, value|
+ pattern = "%#{Query.sanitize_sql_like(value)}%"
+ table = Query.arel_table
+ scope.where(table[:name].matches(pattern).or(table[:description].matches(pattern)))
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/config/routes.rb b/plugins/discourse-data-explorer/config/routes.rb
index 2391d1c4697..6d0f8606cfb 100644
--- a/plugins/discourse-data-explorer/config/routes.rb
+++ b/plugins/discourse-data-explorer/config/routes.rb
@@ -19,6 +19,9 @@ DiscourseDataExplorer::Engine.routes.draw do
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 "/g/:group_name/reports" => "discourse_data_explorer/query#group_reports_index"
get "/g/:group_name/reports/:id" => "discourse_data_explorer/query#group_reports_show"
post "/g/:group_name/reports/:id/run" => "discourse_data_explorer/query#group_reports_run"
diff --git a/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb
new file mode 100644
index 00000000000..4132dca7935
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb
@@ -0,0 +1,325 @@
+# frozen_string_literal: true
+
+RSpec.describe "JSON:API queries", type: :request do
+ fab!(:admin)
+ fab!(:author) { Fabricate(:user, username: "query_author") }
+ fab!(:oldest) do
+ Fabricate(
+ :query,
+ name: "Posts of the week",
+ description: "Every post written in the last seven days",
+ sql: "SELECT id FROM posts LIMIT 1",
+ user: author,
+ last_run_at: Time.utc(2026, 8, 1),
+ )
+ end
+ fab!(:middle) do
+ Fabricate(
+ :query,
+ name: "Users who never posted",
+ description: "Accounts with no post at all",
+ sql: "SELECT id FROM users LIMIT 2",
+ user: author,
+ last_run_at: Time.utc(2026, 8, 2),
+ )
+ end
+ fab!(:newest) do
+ Fabricate(
+ :query,
+ name: "Topics of a category",
+ description: "Every topic filed under one category",
+ sql: "SELECT id FROM topics LIMIT 3",
+ user: author,
+ last_run_at: Time.utc(2026, 8, 3),
+ )
+ end
+
+ fab!(:analysts) { Fabricate(:group, name: "analysts") }
+
+ before { [oldest, middle, newest].each { Fabricate(:query_group, query: it, group: analysts) } }
+
+ let(:base) { "http://test.localhost/api/data-explorer" }
+ let(:root) { "http://test.localhost/api" }
+ let(:query_parameters) { {} }
+ let(:user) { admin }
+ let(:parsed_body) { JSON.parse(response.body) }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ sign_in(user)
+ get path, params: query_parameters
+ end
+
+ shared_examples "a request only for admins" do
+ context "when the user is not an admin" do
+ fab!(:visitor, :user)
+
+ let(:user) { visitor }
+
+ it { expect(response).to have_http_status(:forbidden) }
+
+ it "sends the reason" do
+ expect(parsed_body["errors"].sole).to eq(
+ "status" => "403",
+ "title" => "Forbidden",
+ "detail" => "You are not allowed to make this request.",
+ )
+ end
+ end
+ end
+
+ describe "GET /index" do
+ let(:path) { "/api/data-explorer/queries" }
+ let(:data) do
+ [newest, middle, oldest].map do |query|
+ {
+ "type" => "queries",
+ "id" => query.id.to_s,
+ "attributes" => {
+ "name" => query.name,
+ "description" => query.description,
+ "sql" => query.sql,
+ "param_info" => [],
+ "is_default" => false,
+ "created_at" => query.created_at.as_json,
+ "last_run_at" => query.last_run_at.as_json,
+ },
+ "links" => {
+ "self" => "#{base}/queries/#{query.id}",
+ },
+ }
+ end
+ end
+ let(:links) do
+ {
+ "self" => {
+ "href" => "#{base}/queries",
+ "type" => JsonApiKit::Pagination::Profile::MEDIA_TYPE,
+ },
+ "prev" => nil,
+ "next" => nil,
+ }
+ end
+
+ it_behaves_like "a request only for admins"
+
+ it "sends the first page of queries" do
+ expect(parsed_body).to eq("data" => data, "included" => [], "links" => links)
+ end
+
+ context "when the request sorts by name" do
+ let(:query_parameters) { { sort: "name" } }
+
+ it "sends the queries in that order" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(
+ ["Posts of the week", "Topics of a category", "Users who never posted"],
+ )
+ end
+ end
+
+ context "when the request sorts by the author's username" do
+ fab!(:later_author) { Fabricate(:user, username: "zoe_analyst") }
+ fab!(:by_zoe) { Fabricate(:query, name: "Written by Zoe", user: later_author) }
+ fab!(:by_nobody) { Fabricate(:query, name: "Written by nobody", user: nil) }
+
+ let(:query_parameters) { { sort: "user.username" } }
+
+ it "sends the queries in that order, and the ones with no author last" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(
+ [
+ "Posts of the week",
+ "Users who never posted",
+ "Topics of a category",
+ "Written by Zoe",
+ "Written by nobody",
+ ],
+ )
+ end
+ end
+
+ context "when the request filters by a word in the name" do
+ let(:query_parameters) { { filter: { search: "NEVER POSTED" } } }
+
+ it "sends the queries that match, whatever the case" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(
+ ["Users who never posted"],
+ )
+ end
+ end
+
+ context "when the request filters by a word in the description" do
+ let(:query_parameters) { { filter: { search: "seven days" } } }
+
+ it "sends the queries that match" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(["Posts of the week"])
+ end
+ end
+
+ context "when the filter value holds a wildcard character" do
+ let(:query_parameters) { { filter: { search: "%" } } }
+
+ it "reads it as a plain character" do
+ expect(parsed_body["data"]).to be_empty
+ end
+ end
+
+ context "when the request limits the page size to 1" do
+ let(:query_parameters) { { page: { size: "1" } } }
+ let(:order) { DiscourseDataExplorer::QueryResource.order.first }
+ let(:cursor) { order.position_of(newest).to_cursor.to_s }
+ let(:next_page) { "#{base}/queries?#{{ page: { after: cursor, size: "1" } }.to_query}" }
+
+ it "sends that many queries" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(["Topics of a category"])
+ end
+
+ it "links to the next page" do
+ expect(parsed_body["links"]).to eq(
+ "self" => {
+ "href" => "#{base}/queries?page%5Bsize%5D=1",
+ "type" => JsonApiKit::Pagination::Profile::MEDIA_TYPE,
+ },
+ "prev" => nil,
+ "next" => next_page,
+ )
+ end
+ end
+
+ context "when the request doesn’t limit the page size" do
+ fab!(:filler) do
+ DiscourseDataExplorer::Query.insert_all(
+ (1..60).map do
+ {
+ name: "Filler #{it}",
+ sql: "SELECT 1",
+ created_at: Time.utc(2026, 7, 1),
+ updated_at: Time.utc(2026, 7, 1),
+ }
+ end,
+ )
+ end
+
+ it "sends fifty queries" do
+ expect(parsed_body["data"].size).to eq(50)
+ end
+ end
+
+ context "when the request anchors the page on one query" do
+ let(:query_parameters) do
+ { sort: "name", page: { anchor: { id: middle.id }, before_size: "1", after_size: "0" } }
+ end
+
+ it "sends the page around that query" do
+ expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(
+ ["Topics of a category", "Users who never posted"],
+ )
+ end
+ end
+
+ context "when the request includes the author and the groups" do
+ let(:query_parameters) { { include: "user,groups" } }
+ let(:relationships) do
+ [newest, middle, oldest].map do |query|
+ {
+ "user" => {
+ "data" => {
+ "type" => "users",
+ "id" => author.id.to_s,
+ },
+ "links" => {
+ "self" => "#{base}/queries/#{query.id}/relationships/user",
+ "related" => "#{base}/queries/#{query.id}/user",
+ },
+ },
+ "groups" => {
+ "data" => [{ "type" => "groups", "id" => analysts.id.to_s }],
+ "links" => {
+ "self" => "#{base}/queries/#{query.id}/relationships/groups",
+ "related" => "#{base}/queries/#{query.id}/groups",
+ "prev" => nil,
+ "next" => nil,
+ },
+ },
+ }
+ end
+ end
+
+ it "links every query to its author and to its groups" do
+ expect(parsed_body["data"].map { it["relationships"] }).to eq(relationships)
+ end
+
+ it "sends every related record under its own namespace" do
+ expect(parsed_body["included"]).to contain_exactly(
+ {
+ "type" => "users",
+ "id" => author.id.to_s,
+ "attributes" => {
+ "username" => "query_author",
+ },
+ "links" => {
+ "self" => "#{root}/users/#{author.id}",
+ },
+ },
+ {
+ "type" => "groups",
+ "id" => analysts.id.to_s,
+ "attributes" => {
+ "name" => "analysts",
+ },
+ "links" => {
+ "self" => "#{root}/groups/#{analysts.id}",
+ },
+ },
+ )
+ end
+ end
+ end
+
+ describe "GET /show" do
+ let(:path) { "/api/data-explorer/queries/#{middle.id}" }
+
+ it_behaves_like "a request only for admins"
+
+ it "sends one query" do
+ expect(parsed_body).to eq(
+ "data" => {
+ "type" => "queries",
+ "id" => middle.id.to_s,
+ "attributes" => {
+ "name" => middle.name,
+ "description" => middle.description,
+ "sql" => middle.sql,
+ "param_info" => [],
+ "is_default" => false,
+ "created_at" => middle.created_at.as_json,
+ "last_run_at" => middle.last_run_at.as_json,
+ },
+ "links" => {
+ "self" => "#{base}/queries/#{middle.id}",
+ },
+ },
+ "included" => [],
+ "links" => {
+ "self" => {
+ "href" => "#{base}/queries/#{middle.id}",
+ "type" => JsonApiKit::Pagination::Profile::MEDIA_TYPE,
+ },
+ },
+ )
+ end
+
+ context "when no query has that id" do
+ let(:path) { "/api/data-explorer/queries/0" }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+
+ context "when the query is hidden" do
+ fab!(:secret) { Fabricate(:query, name: "Hidden from the listing", hidden: true) }
+
+ let(:path) { "/api/data-explorer/queries/#{secret.id}" }
+
+ it { expect(response).to have_http_status(:not_found) }
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/endpoint_spec.rb b/spec/integration/json_api_kit/endpoint_spec.rb
index ee88e67c4f7..1fa1031a3d1 100644
--- a/spec/integration/json_api_kit/endpoint_spec.rb
+++ b/spec/integration/json_api_kit/endpoint_spec.rb
@@ -4,28 +4,12 @@ require_relative "support"
module JsonApiKitSpec
class TopicsController < JsonApiKit::BaseController
- def index
- render_document(
- JsonApiKit::Document::Collection.for(
- request.query_parameters,
- resource: TopicResource,
- guardian:,
- urls:,
- ),
- )
- end
+ resource :topics
+ end
+end
- def show
- render_document(
- JsonApiKit::Document::Individual.for(
- params[:id],
- request.query_parameters,
- resource: TopicResource,
- guardian:,
- urls:,
- ),
- )
- end
+module JsonApiKitSpec
+ class UndeclaredController < JsonApiKit::BaseController
end
end
@@ -53,10 +37,12 @@ RSpec.describe "a JSON:API endpoint", type: :request do
let(:error) { parsed_body["errors"].sole }
before do
+ allow(Discourse).to receive(:warn_exception)
Rails.application.routes.disable_clear_and_finalize = true
Rails.application.routes.draw do
get "/api/topics" => "json_api_kit_spec/topics#index"
get "/api/topics/:id" => "json_api_kit_spec/topics#show"
+ get "/api/undeclared" => "json_api_kit_spec/undeclared#index"
get "/api/failing" => "json_api_kit_spec/failing#index"
get "/api/missing" => "json_api_kit_spec/failing#show"
get "/api/forbidden" => "json_api_kit_spec/failing#forbidden"
@@ -67,6 +53,37 @@ RSpec.describe "a JSON:API endpoint", type: :request do
after { Rails.application.reload_routes! }
+ describe "the resource a controller serves" do
+ it "registers the resource that name matches" do
+ expect(JsonApiKitSpec::TopicsController.declared_resource).to eq(
+ JsonApiKitSpec::TopicResource,
+ )
+ end
+
+ context "when the controller names the class itself" do
+ subject(:controller) do
+ Class.new(JsonApiKit::BaseController) { resource JsonApiKitSpec::TopicResource }
+ end
+
+ it "registers that class" do
+ expect(controller.declared_resource).to eq(JsonApiKitSpec::TopicResource)
+ end
+ end
+
+ context "when the controller declares none" do
+ let(:path) { "/api/undeclared" }
+
+ it { expect(response).to have_http_status(:internal_server_error) }
+
+ it "reports a missing declaration" do
+ expect(Discourse).to have_received(:warn_exception) do |error, _|
+ expect(error).to be_a(JsonApiKit::BaseController::MissingDeclaration)
+ expect(error.message).to match(/declare the resource it serves/)
+ end
+ end
+ end
+ end
+
describe "the response" do
it "sends the JSON:API media type" do
expect(response.media_type).to eq(profile_media_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 8e6f7fe997e..aa7cf914e0b 100644
--- a/spec/lib/json_api_kit/document/relationship_object_spec.rb
+++ b/spec/lib/json_api_kit/document/relationship_object_spec.rb
@@ -35,8 +35,10 @@ RSpec.describe JsonApiKit::Document::RelationshipObject do
JsonApiKit::Pagination::Row.new(record: topic, segment: nil),
topics_resource.fields(guardian:),
type: "topics",
+ namespace:,
)
end
+ let(:namespace) { nil }
let(:linkage) { JsonApiKit::Linkage::ToOne.new([record]) }
let(:relationship_url) { "https://example.com/api/topics/#{topic.id}/relationships/posts" }
let(:related_url) { "https://example.com/api/topics/#{topic.id}/posts" }
@@ -50,6 +52,17 @@ RSpec.describe JsonApiKit::Document::RelationshipObject do
expect(relationship_object.to_h[:links]).to eq(self: relationship_url, related: related_url)
end
+ context "with a namespace" do
+ let(:namespace) { "data-explorer" }
+
+ it "renders both links under it" do
+ expect(relationship_object.to_h[:links]).to eq(
+ self: "https://example.com/api/data-explorer/topics/#{topic.id}/relationships/posts",
+ related: "https://example.com/api/data-explorer/topics/#{topic.id}/posts",
+ )
+ end
+ end
+
context "when the relationship holds a page of records" do
let(:page) do
JsonApiKit::Records::Page.new(JsonApiKit::Records.new([record]), "read-on-here")
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 068b8b0f52b..38fe19014de 100644
--- a/spec/lib/json_api_kit/document/resource_object_spec.rb
+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb
@@ -43,6 +43,18 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
end
end
+ context "with a namespace" do
+ let(:record) do
+ JsonApiKit::Record.new(row, fields, type: "topics", namespace: "data-explorer")
+ end
+
+ it "renders the self link under it" do
+ expect(resource_object.to_h[:links]).to eq(
+ self: "https://example.com/api/data-explorer/topics/#{topic.id}",
+ )
+ end
+ end
+
context "when the record holds no attribute" do
let(:fields) { resource.fields(["secrets"], guardian:) }
diff --git a/spec/lib/json_api_kit/record_spec.rb b/spec/lib/json_api_kit/record_spec.rb
index 33304fb59cd..552b53c8fdc 100644
--- a/spec/lib/json_api_kit/record_spec.rb
+++ b/spec/lib/json_api_kit/record_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe JsonApiKit::Record do
subject(:record) do
- described_class.new(row, resource.fields(guardian:), type: "topics", relationships:)
+ described_class.new(row, resource.fields(guardian:), type: "topics", namespace:, relationships:)
end
fab!(:author, :user)
@@ -32,6 +32,7 @@ RSpec.describe JsonApiKit::Record do
)
end
let(:relationships) { {} }
+ let(:namespace) { nil }
describe "#attributes" do
it "renders the fields that the resource declares" do
@@ -45,6 +46,20 @@ RSpec.describe JsonApiKit::Record do
end
end
+ describe "#namespace" do
+ subject(:namespace_of) { record.namespace }
+
+ context "without a namespace" do
+ it { is_expected.to be_nil }
+ end
+
+ context "with a namespace" do
+ let(:namespace) { "data-explorer" }
+
+ it { is_expected.to eq("data-explorer") }
+ end
+ end
+
describe "#identity" do
it "returns the type and the id" do
expect(record.identity).to eq(
@@ -97,6 +112,14 @@ RSpec.describe JsonApiKit::Record do
expect(merged.relationships["user"].collapse { it.id }).to eq(author.id.to_s)
end
end
+
+ context "with a namespace" do
+ let(:namespace) { "data-explorer" }
+
+ it "keeps it" do
+ expect(merged.namespace).to eq("data-explorer")
+ end
+ end
end
describe "#related_records" do
diff --git a/spec/lib/json_api_kit/record_url_spec.rb b/spec/lib/json_api_kit/record_url_spec.rb
new file mode 100644
index 00000000000..0f802a700b4
--- /dev/null
+++ b/spec/lib/json_api_kit/record_url_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::RecordUrl do
+ subject(:url) { described_class.new(base, record) }
+
+ let(:base) { "https://example.com/api" }
+ let(:namespace) { nil }
+ let(:record) { instance_double(JsonApiKit::Record, namespace:, type: "topics", id: "5") }
+
+ describe "#to_s" do
+ subject(:address) { url.to_s }
+
+ it { is_expected.to eq("https://example.com/api/topics/5") }
+
+ context "with a namespace" do
+ let(:namespace) { "data-explorer" }
+
+ it { is_expected.to eq("https://example.com/api/data-explorer/topics/5") }
+ end
+ end
+
+ describe "#relationship" do
+ subject(:address) { url.relationship("posts").to_s }
+
+ it { is_expected.to eq("https://example.com/api/topics/5/relationships/posts") }
+ end
+
+ describe "#related" do
+ subject(:address) { url.related("posts").to_s }
+
+ it { is_expected.to eq("https://example.com/api/topics/5/posts") }
+ end
+end
diff --git a/spec/lib/json_api_kit/resource_lookup_spec.rb b/spec/lib/json_api_kit/resource_lookup_spec.rb
new file mode 100644
index 00000000000..120c93218ac
--- /dev/null
+++ b/spec/lib/json_api_kit/resource_lookup_spec.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+class SpecOrphanResource < JsonApiKit::Resource
+end
+
+class SpecImpostorResource
+end
+
+class SpecTwinResource < JsonApiKit::Resource
+end
+
+module SpecLookup
+ class UserResource < JsonApiKit::Resource
+ end
+
+ class SpecTwinResource < JsonApiKit::Resource
+ end
+
+ class QueryResource < JsonApiKit::Resource
+ end
+end
+
+RSpec.describe JsonApiKit::ResourceLookup do
+ subject(:found) { described_class.resource(declaration, within: SpecLookup::QueryResource) }
+
+ let(:declaration) { :user }
+
+ context "when the resource is in the same namespace" do
+ it { is_expected.to eq(SpecLookup::UserResource) }
+ end
+
+ context "with a plural name" do
+ let(:declaration) { :users }
+
+ it { is_expected.to eq(SpecLookup::UserResource) }
+ end
+
+ context "when the resource is at the root" do
+ let(:declaration) { :spec_orphan }
+
+ it { is_expected.to eq(SpecOrphanResource) }
+ end
+
+ context "when the resource is in both" do
+ let(:declaration) { :spec_twin }
+
+ it "prefers the same namespace" do
+ expect(found).to eq(SpecLookup::SpecTwinResource)
+ end
+ end
+
+ context "when the resource doesn’t exist" do
+ let(:declaration) { :author }
+
+ it do
+ expect { found }.to raise_error(
+ described_class::MissingResource,
+ "SpecLookup::QueryResource: no resource is named author, " \
+ "tried SpecLookup::AuthorResource, AuthorResource",
+ )
+ end
+ end
+
+ context "with a resource class" do
+ let(:declaration) { SpecOrphanResource }
+
+ it { is_expected.to eq(SpecOrphanResource) }
+ end
+
+ context "with another kind of class" do
+ let(:declaration) { Topic }
+
+ it do
+ expect { found }.to raise_error(
+ described_class::UnsupportedResource,
+ "SpecLookup::QueryResource: Topic is not a JSON:API resource",
+ )
+ end
+ end
+
+ context "with a name matching another kind of class" do
+ let(:declaration) { :spec_impostor }
+
+ it do
+ expect { found }.to raise_error(
+ described_class::UnsupportedResource,
+ "SpecLookup::QueryResource: SpecImpostorResource is not a JSON:API resource",
+ )
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/resource_spec.rb b/spec/lib/json_api_kit/resource_spec.rb
index 0a8c6e97cca..4f775e790a9 100644
--- a/spec/lib/json_api_kit/resource_spec.rb
+++ b/spec/lib/json_api_kit/resource_spec.rb
@@ -11,6 +11,18 @@ module SpecBlog
class UnbackedResource < JsonApiKit::Resource
end
+
+ class AuthorResource < JsonApiKit::Resource
+ model User
+ type :authors
+ end
+
+ class ArticleResource < JsonApiKit::Resource
+ model Topic
+ type :articles
+ has_one :author
+ has_many :authors
+ end
end
RSpec.describe JsonApiKit::Resource do
@@ -188,6 +200,42 @@ RSpec.describe JsonApiKit::Resource do
end
end
+ describe ".namespace" do
+ subject(:namespace) { resource.namespace }
+
+ context "when the resource declares none" do
+ it "returns nothing" do
+ expect(namespace).to be_nil
+ end
+ end
+
+ context "when the resource declares one" do
+ subject(:resource) { Class.new(described_class) { namespace :internal } }
+
+ it "returns the namespace as a string" do
+ expect(namespace).to eq("internal")
+ end
+ end
+
+ context "when a resource inherits from another" do
+ subject(:resource) { Class.new(parent) }
+
+ let(:parent) { Class.new(described_class) { namespace "data-explorer" } }
+
+ it "returns its parent's namespace" do
+ expect(namespace).to eq("data-explorer")
+ end
+
+ context "when it declares a namespace of its own" do
+ before { resource.namespace("internal") }
+
+ it "leaves its parent's namespace alone" do
+ expect(parent.namespace).to eq("data-explorer")
+ end
+ end
+ end
+ end
+
describe ".schema" do
it "returns a schema for the model it exposes" do
expect(topic_resource.schema.model).to eq(Topic)
@@ -326,6 +374,24 @@ RSpec.describe JsonApiKit::Resource do
expect(category_relationships.map(&:name)).to eq(%w[category])
end
end
+
+ context "without a resource" do
+ subject(:author_relationships) do
+ SpecBlog::ArticleResource.fields(guardian:).relationships.pick(%w[author])
+ end
+
+ it "infers it from the name" do
+ expect(author_relationships.first.resource).to eq(SpecBlog::AuthorResource)
+ end
+ end
+
+ context "when no resource matches the name" do
+ it do
+ expect { Class.new(described_class) { has_one :nobody } }.to raise_error(
+ JsonApiKit::ResourceLookup::MissingResource,
+ )
+ end
+ end
end
describe ".has_many" do
@@ -334,6 +400,16 @@ RSpec.describe JsonApiKit::Resource do
it "relates the resource to many records of another" do
expect(posts_relationships.first).to be_a(JsonApiKit::Declarations::Relationship::ToMany)
end
+
+ context "without a resource" do
+ subject(:author_relationships) do
+ SpecBlog::ArticleResource.fields(guardian:).relationships.pick(%w[authors])
+ end
+
+ it "infers it from the singular name" do
+ expect(author_relationships.first.resource).to eq(SpecBlog::AuthorResource)
+ end
+ end
end
describe ".resolves?" do
diff --git a/spec/lib/json_api_kit/urls_spec.rb b/spec/lib/json_api_kit/urls_spec.rb
index bfc1cc048a5..cc212b7886e 100644
--- a/spec/lib/json_api_kit/urls_spec.rb
+++ b/spec/lib/json_api_kit/urls_spec.rb
@@ -15,31 +15,11 @@ RSpec.describe JsonApiKit::Urls do
end
end
- describe "#record" do
- it "returns the URL of one record" do
- expect(urls.record("topics", "5").to_s).to eq("https://example.com/api/topics/5")
- end
-
- it "carries only the cursor a caller adds" do
- expect(urls.record("topics", "5").at(after: "a-cursor").to_s).to eq(
- "https://example.com/api/topics/5?page%5Bafter%5D=a-cursor",
- )
- end
- end
+ describe "#for" do
+ subject(:address) { urls.for(record).to_s }
- describe "#relationship" do
- it "returns the URL of the relationship itself" do
- expect(urls.relationship("topics", "5", "posts").to_s).to eq(
- "https://example.com/api/topics/5/relationships/posts",
- )
- end
- end
+ let(:record) { instance_double(JsonApiKit::Record, namespace: nil, type: "topics", id: "5") }
- describe "#related" do
- it "returns the URL of the records a relationship points at" do
- expect(urls.related("topics", "5", "posts").to_s).to eq(
- "https://example.com/api/topics/5/posts",
- )
- end
+ it { is_expected.to eq("https://example.com/api/topics/5") }
end
end
diff --git a/spec/resources/group_resource_spec.rb b/spec/resources/group_resource_spec.rb
new file mode 100644
index 00000000000..2fa28291f84
--- /dev/null
+++ b/spec/resources/group_resource_spec.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+RSpec.describe GroupResource do
+ fab!(:group) { Fabricate(:group, name: "a_group") }
+
+ let(:guardian) { Guardian.new }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/groups")
+ end
+ let(:document) do
+ JsonApiKit::Document::Individual.for(group.id, {}, resource: described_class, guardian:, urls:)
+ end
+
+ it "shows the name and nothing else" do
+ expect(document.to_h[:data]).to eq(
+ type: "groups",
+ id: group.id.to_s,
+ attributes: {
+ "name" => "a_group",
+ },
+ links: {
+ self: "https://example.com/api/groups/#{group.id}",
+ },
+ )
+ end
+end
diff --git a/spec/resources/user_resource_spec.rb b/spec/resources/user_resource_spec.rb
new file mode 100644
index 00000000000..3403f7fa216
--- /dev/null
+++ b/spec/resources/user_resource_spec.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+RSpec.describe UserResource do
+ fab!(:user) { Fabricate(:user, username: "someone") }
+
+ let(:guardian) { Guardian.new }
+ let(:urls) do
+ JsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/users")
+ end
+ let(:document) do
+ JsonApiKit::Document::Individual.for(user.id, {}, resource: described_class, guardian:, urls:)
+ end
+
+ it "shows the username and nothing else" do
+ expect(document.to_h[:data]).to eq(
+ type: "users",
+ id: user.id.to_s,
+ attributes: {
+ "username" => "someone",
+ },
+ links: {
+ self: "https://example.com/api/users/#{user.id}",
+ },
+ )
+ end
+end