15 minute fix: Add default argument to JsonApiSortParam (#13369)

* Add default argument to JsonApiSortParam

* Update usage
This commit is contained in:
Michael Kohl 2021-04-14 10:32:07 +07:00 committed by GitHub
parent 208d788672
commit dc16b94f83
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 3 deletions

View file

@ -29,7 +29,6 @@ module Api
def order_criteria
parse_sort_param(
params[:sort],
allowed_fields: [:created_at],
default_sort: { created_at: :desc },
)

View file

@ -6,7 +6,7 @@ module JsonApiSortParam
# array determines the sort order of the resulting hash.
# @param default_sort [{Symbol => Symbol}] The default sort order. Used when
# the param string is nil/empty or when parsing it results in an empty hash.
def parse_sort_param(param_string, allowed_fields:, default_sort:)
def parse_sort_param(param_string = params[:sort], allowed_fields:, default_sort:)
fields = param_string.to_s.split(",")
unfiltered_hash = fields_to_hash(fields)
sort = sort_and_filter(unfiltered_hash, allowed_fields)

View file

@ -1,7 +1,20 @@
require "rails_helper"
RSpec.describe JsonApiSortParam do
let!(:controller) { Class.new { include JsonApiSortParam }.new }
let!(:controller) do
Class.new(Api::V0::ApiController) { include JsonApiSortParam }.new
end
it "uses the `sort` param of the controller by default" do
params = ActionController::Parameters.new(sort: "created_at,-updated_at")
allow(controller).to receive(:params).and_return(params)
params = controller.parse_sort_param(
allowed_fields: %i[created_at updated_at],
default_sort: { created_at: :desc },
)
expect(params).to eq({ created_at: :asc, updated_at: :desc })
end
it "returns a default sort order if there are no sorting params" do
params = controller.parse_sort_param(