A platform for community discussion. Free, open, simple.
DEV: Add a JSON:API Kit base controller (#42793)
Loïc Guitaut228ab8f7e0f9
diff --git a/app/controllers/json_api_kit/base_controller.rb b/app/controllers/json_api_kit/base_controller.rbnew file mode 100644index 00000000000..3639ff8b3c1--- /dev/null+++ b/app/controllers/json_api_kit/base_controller.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController < ::ApplicationController+ ROOT = "/api"+ OTHER_PARAMETER = "Content-Type accepts the ext and profile parameters only."+ NO_EXTENSION = "This API applies no extension."+ UNREADABLE_ACCEPT =+ "Accept must allow #{MediaType::JSON_API} with the ext and profile parameters only."++ skip_before_action :check_xhr,+ :redirect_to_login_if_required,+ :verify_authenticity_token,+ raise: 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)) }++ def rescue_with_handler(*)+ super || render_server_error(*)+ end++ private++ def urls+ Urls.new(+ base: "#{request.base_url}#{ROOT}",+ current: "#{request.base_url}#{request.path}",+ parameters: request.query_parameters,+ )+ end++ def set_json_format = request.format = :json++ def set_vary_header = response.headers["Vary"] ||= "Accept"++ def render_server_error(error)+ Discourse.warn_exception(error, message: "JSON:API request failed")+ render_document(Document::Errors.new(InternalServerError.new))+ end++ def render_document(document)+ render json: document.to_h, status: document.status, content_type: MediaType::JSON_API+ end++ def negotiate+ (content_type_refusal || accept_refusal).try { render_document(Document::Errors.new(it)) }+ end++ def content_type_refusal+ return unless request_media_type&.json_api?+ return UnsupportedMediaType.new(OTHER_PARAMETER) if request_media_type.modified?+ UnsupportedMediaType.new(NO_EXTENSION) if request_media_type.extended?+ end++ def accept_refusal+ return if accepted_media_types.empty? || accepted_media_types.any? { !it.modified? }+ NotAcceptable.new(UNREADABLE_ACCEPT)+ end++ def request_media_type+ @request_media_type ||= MediaType.parse(request.headers["Content-Type"]).first+ end++ def accepted_media_types+ @accepted_media_types ||= MediaType.parse(request.headers["Accept"]).select(&:json_api?)+ end+ end+enddiff --git a/lib/json_api_kit/forbidden.rb b/lib/json_api_kit/forbidden.rbnew file mode 100644index 00000000000..0ecc144c3cb--- /dev/null+++ b/lib/json_api_kit/forbidden.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++module JsonApiKit+ class Forbidden < Error+ def initialize(detail = "You are not allowed to make this request.")+ super+ end++ def status = "403"++ def title = "Forbidden"+ end+enddiff --git a/lib/json_api_kit/internal_server_error.rb b/lib/json_api_kit/internal_server_error.rbnew file mode 100644index 00000000000..f781a0517fe--- /dev/null+++ b/lib/json_api_kit/internal_server_error.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++module JsonApiKit+ class InternalServerError < Error+ def initialize(detail = "The server could not answer this request.")+ super+ end++ def status = "500"++ def title = "Internal server error"+ end+enddiff --git a/lib/json_api_kit/media_type.rb b/lib/json_api_kit/media_type.rbnew file mode 100644index 00000000000..ee14ffdc021--- /dev/null+++ b/lib/json_api_kit/media_type.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module JsonApiKit+ class MediaType+ JSON_API = "application/vnd.api+json"+ ALLOWED = %w[ext profile].freeze+ WEIGHT = "q"++ def self.parse(header) = header.to_s.split(",").filter_map { new(it) if it.present? }++ def initialize(declaration)+ @declaration = declaration.strip+ end++ def json_api? = Rack::MediaType.type(declaration) == JSON_API++ def modified? = (names - ALLOWED).any?++ def extended? = names.include?("ext")++ private++ attr_reader :declaration++ def names = @names ||= Rack::MediaType.params(declaration).keys - [WEIGHT]+ end+enddiff --git a/lib/json_api_kit/not_acceptable.rb b/lib/json_api_kit/not_acceptable.rbnew file mode 100644index 00000000000..939deef2d62--- /dev/null+++ b/lib/json_api_kit/not_acceptable.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module JsonApiKit+ class NotAcceptable < Error+ def status = "406"++ def title = "Not acceptable"+ end+enddiff --git a/lib/json_api_kit/unsupported_media_type.rb b/lib/json_api_kit/unsupported_media_type.rbnew file mode 100644index 00000000000..fe7beccf9d2--- /dev/null+++ b/lib/json_api_kit/unsupported_media_type.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module JsonApiKit+ class UnsupportedMediaType < Error+ def status = "415"++ def title = "Unsupported media type"+ end+enddiff --git a/spec/integration/json_api_kit/endpoint_spec.rb b/spec/integration/json_api_kit/endpoint_spec.rbnew file mode 100644index 00000000000..88e68798ea9--- /dev/null+++ b/spec/integration/json_api_kit/endpoint_spec.rb@@ -0,0 +1,310 @@+# frozen_string_literal: true++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++ def show+ render_document(+ JsonApiKit::Document::Individual.for(+ params[:id],+ request.query_parameters,+ resource: TopicResource,+ guardian:,+ urls:,+ ),+ )+ end+ end+end++module JsonApiKitSpec+ class FailingController < JsonApiKit::BaseController+ def index = raise "the reason nobody planned for"++ def show = raise Discourse::NotFound++ def forbidden = raise Discourse::InvalidAccess+ end+end++RSpec.describe "a JSON:API endpoint", type: :request do+ include_context "with a listing of topics"++ let(:base) { "http://test.localhost/api" }+ let(:current) { "#{base}/topics" }+ let(:media_type) { "application/vnd.api+json" }+ let(:profile) { "https://jsonapi.org/profiles/ethanresnick/cursor-pagination" }+ let(:path) { "/api/topics" }+ let(:headers) { {} }+ let(:parsed_body) { JSON.parse(response.body) }+ let(:error) { parsed_body["errors"].sole }++ before do+ 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/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"+ end+ Rails.application.routes.disable_clear_and_finalize = false+ get path, headers:, params: query+ end++ after { Rails.application.reload_routes! }++ describe "the response" do+ it "sends the JSON:API media type" do+ expect(response.media_type).to eq(media_type)+ end++ it "varies on the accept header" do+ expect(response.headers["Vary"]).to include("Accept")+ end++ context "when the path ends with a format" do+ let(:path) { "/api/topics.json" }++ it "sends the JSON:API media type" do+ expect(response.media_type).to eq(media_type)+ end++ it "varies on the accept header" do+ expect(response.headers["Vary"]).to include("Accept")+ end+ end++ context "when the content type carries another parameter" do+ let(:headers) { { "CONTENT_TYPE" => "#{media_type};charset=utf-8" } }++ it "varies on the accept header" do+ expect(response.headers["Vary"]).to include("Accept")+ end+ end+ end++ describe "fetching a collection" do+ let(:query) { { "page" => { "size" => "2" }, "fields" => { "topics" => "title" } } }+ let(:fields) { %w[title] }++ it "sends the first page of the collection" do+ expect(parsed_body).to eq(+ {+ data: [topic_object(newest, fields:), topic_object(middle, fields:)],+ included: [],+ links: links_of(next: page_url(after: cursor_of_record(middle), size: 2)),+ }.deep_stringify_keys,+ )+ end++ context "when the request anchors the page on one row" do+ let(:query) do+ {+ "sort" => "created_at",+ "page" => {+ "anchor" => {+ "id" => oldest.id.to_s,+ },+ "before_size" => "0",+ "after_size" => "1",+ },+ }+ end+ let(:next_link) { URI.parse(parsed_body.dig("links", "next")) }++ it "sends the rows after the window when a client follows the next link" do+ get "#{next_link.path}?#{next_link.query}"++ expect(JSON.parse(response.body)["data"].map { it["id"] }).to eq([newest.id.to_s])+ end+ end++ context "when the request sorts by title" do+ let(:query) { { "sort" => "title", "fields" => { "topics" => "title" } } }+ let(:sort) { { "title" => :asc } }++ it "sends the rows in that order" do+ expect(parsed_body).to eq(+ {+ data: [+ topic_object(oldest, fields:),+ topic_object(newest, fields:),+ topic_object(middle, fields:),+ ],+ included: [],+ links: links_of,+ }.deep_stringify_keys,+ )+ end+ end+ end++ describe "fetching one record" do+ let(:path) { "/api/topics/#{middle.id}" }+ let(:current) { "#{base}/topics/#{middle.id}" }+ let(:query) { { "fields" => { "topics" => "title" } } }++ it "sends the record" do+ expect(parsed_body).to eq(+ {+ data: topic_object(middle, fields: %w[title]),+ included: [],+ links: {+ self: self_link,+ },+ }.deep_stringify_keys,+ )+ end++ context "when no record has that id" do+ let(:path) { "/api/topics/0" }++ it { expect(response).to have_http_status(:not_found) }++ it "sends the reason" do+ expect(error).to eq(not_found.deep_stringify_keys)+ end+ end+ end++ describe "an unexpected error" do+ let(:path) { "/api/failing" }++ it { expect(response).to have_http_status(:internal_server_error) }++ it "sends the JSON:API media type" do+ expect(response.media_type).to eq(media_type)+ end++ it "sends the reason" do+ expect(error).to eq(+ "status" => "500",+ "title" => "Internal server error",+ "detail" => "The server could not answer this request.",+ )+ end++ context "when Discourse answers the error itself" do+ let(:path) { "/api/missing" }++ it { expect(response).to have_http_status(:not_found) }++ it "sends JSON" do+ expect(response.media_type).to eq("application/json")+ end+ end+ end++ describe "a request Discourse refuses" do+ let(:path) { "/api/forbidden" }++ it { expect(response).to have_http_status(:forbidden) }++ it "sends the JSON:API media type" do+ expect(response.media_type).to eq(media_type)+ end++ it "sends the reason" do+ expect(error).to eq(+ "status" => "403",+ "title" => "Forbidden",+ "detail" => "You are not allowed to make this request.",+ )+ end+ end++ describe "the content type of a request" do+ context "when there is none" do+ it { expect(response).to have_http_status(:ok) }+ end++ context "when it carries a profile parameter" do+ let(:headers) { { "CONTENT_TYPE" => %(#{media_type};profile="#{profile}") } }++ it { expect(response).to have_http_status(:ok) }+ end++ context "when it carries another parameter" do+ let(:headers) { { "CONTENT_TYPE" => "#{media_type};charset=utf-8" } }++ it { expect(response).to have_http_status(:unsupported_media_type) }++ it "sends the reason" do+ expect(error).to eq(+ "status" => "415",+ "title" => "Unsupported media type",+ "detail" => "Content-Type accepts the ext and profile parameters only.",+ )+ end+ end++ context "when it applies an extension" do+ let(:headers) { { "CONTENT_TYPE" => %(#{media_type};ext="https://example.com/x") } }++ it { expect(response).to have_http_status(:unsupported_media_type) }++ it "sends the reason" do+ expect(error).to eq(+ "status" => "415",+ "title" => "Unsupported media type",+ "detail" => "This API applies no extension.",+ )+ end+ end+ end++ describe "the accept header of a request" do+ context "when it allows the JSON:API media type" do+ let(:headers) { { "HTTP_ACCEPT" => media_type } }++ it { expect(response).to have_http_status(:ok) }+ end++ context "when it allows another media type" do+ let(:headers) { { "HTTP_ACCEPT" => "text/csv" } }++ it { expect(response).to have_http_status(:ok) }+ end++ context "when one instance carries no other parameter" do+ let(:headers) { { "HTTP_ACCEPT" => "#{media_type};charset=utf-8, #{media_type}" } }++ it { expect(response).to have_http_status(:ok) }+ end++ context "when an instance carries a weight" do+ let(:headers) { { "HTTP_ACCEPT" => "#{media_type};q=0.9" } }++ it { expect(response).to have_http_status(:ok) }+ end++ context "when every instance carries another parameter" do+ let(:headers) do+ { "HTTP_ACCEPT" => "#{media_type};charset=utf-8, #{media_type};version=1;q=0.9" }+ end++ it { expect(response).to have_http_status(:not_acceptable) }++ it "sends the reason" do+ expect(error).to eq(+ "status" => "406",+ "title" => "Not acceptable",+ "detail" => "Accept must allow #{media_type} with the ext and profile parameters only.",+ )+ end+ end+ end+enddiff --git a/spec/integration/json_api_kit/support.rb b/spec/integration/json_api_kit/support.rbindex 7184954353c..f0593b94d4c 100644--- a/spec/integration/json_api_kit/support.rb+++ b/spec/integration/json_api_kit/support.rb@@ -188,7 +188,7 @@ RSpec.shared_context "with a listing of topics" dodef links_of(**pages) = { self: self_link, **{ prev: nil, next: nil }.merge(pages) }- def page_url(**page) = "#{current}?#{{ page: page }.to_query}"+ def page_url(**page) = "#{current}?#{query.except("page").merge(page:).to_query}"def cursor_at(index, rendered = document) = cursor_of(rendered[:data][index])diff --git a/spec/lib/json_api_kit/media_type_spec.rb b/spec/lib/json_api_kit/media_type_spec.rbnew file mode 100644index 00000000000..e6fe3fa6f9f--- /dev/null+++ b/spec/lib/json_api_kit/media_type_spec.rb@@ -0,0 +1,77 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::MediaType do+ subject(:media_type) { described_class.new(declaration) }++ let(:declaration) { "application/vnd.api+json" }++ describe ".parse" do+ subject(:parsed) { described_class.parse(header) }++ let(:header) { "application/vnd.api+json;charset=utf-8, application/vnd.api+json" }++ it "returns one media type per instance of the header" do+ expect(parsed.size).to eq(2)+ end++ context "when the header is empty" do+ let(:header) { nil }++ it { is_expected.to be_empty }+ end+ end++ describe "#json_api?" do+ it { is_expected.to be_json_api }++ context "when the letters differ in case" do+ let(:declaration) { "Application/VND.api+JSON" }++ it { is_expected.to be_json_api }+ end++ context "when the media type is another one" do+ let(:declaration) { "text/csv" }++ it { is_expected.not_to be_json_api }+ end+ end++ describe "#modified?" do+ it { is_expected.not_to be_modified }++ context "when a profile is applied" do+ let(:declaration) { %(application/vnd.api+json;profile="https://a/b https://a/c") }++ it { is_expected.not_to be_modified }+ end++ context "when the instance carries a weight" do+ let(:declaration) { "application/vnd.api+json;q=0.9" }++ it { is_expected.not_to be_modified }+ end++ context "when another parameter follows the weight" do+ let(:declaration) { "application/vnd.api+json;q=0.9;charset=utf-8" }++ it { is_expected.to be_modified }+ end++ context "when another parameter comes first" do+ let(:declaration) { "application/vnd.api+json;charset=utf-8" }++ it { is_expected.to be_modified }+ end+ end++ describe "#extended?" do+ it { is_expected.not_to be_extended }++ context "when an extension is applied" do+ let(:declaration) { %(application/vnd.api+json;ext="https://a/b") }++ it { is_expected.to be_extended }+ end+ end+end