Commit b71250ca authored by sujay patel's avatar sujay patel Committed by sujay

Adding order by to list runner jobs api.

parent 2fec78ea
......@@ -3,6 +3,8 @@
class RunnerJobsFinder
attr_reader :runner, :params
ALLOWED_INDEXED_COLUMNS = %w[id created_at].freeze
def initialize(runner, params = {})
@runner = runner
@params = params
......@@ -11,7 +13,7 @@ class RunnerJobsFinder
def execute
items = @runner.builds
items = by_status(items)
items
sort_items(items)
end
private
......@@ -23,4 +25,22 @@ class RunnerJobsFinder
items.where(status: params[:status])
end
# rubocop: enable CodeReuse/ActiveRecord
# rubocop: disable CodeReuse/ActiveRecord
def sort_items(items)
order_by = if ALLOWED_INDEXED_COLUMNS.include?(params[:order_by])
params[:order_by]
else
:id
end
sort = if params[:sort] =~ /\A(ASC|DESC)\z/i
params[:sort]
else
:desc
end
items.order(order_by => sort)
end
# rubocop: enable CodeReuse/ActiveRecord
end
---
title: 51794-add-order-by-to-list-runner-jobs-api
merge_request:
author: Sujay Patel
type: added
......@@ -291,6 +291,8 @@ GET /runners/:id/jobs
|-----------|---------|----------|---------------------|
| `id` | integer | yes | The ID of a runner |
| `status` | string | no | Status of the job; one of: `running`, `success`, `failed`, `canceled` |
| `order_by`| string | no | Order jobs by `id` or `created_at` (default: id) |
| `sort` | string | no | Sort jobs in `asc` or `desc` order (default: `desc`) |
```
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/runners/1/jobs?status=running"
......
......@@ -35,5 +35,42 @@ describe RunnerJobsFinder do
end
end
end
context 'when order_by and sort are specified' do
context 'when order_by created_at' do
let(:params) { { order_by: 'created_at', sort: 'asc' } }
let!(:jobs) { Array.new(2) { create(:ci_build, runner: runner, project: project, user: create(:user)) } }
it 'sorts as created_at: :asc' do
is_expected.to match_array(jobs)
end
context 'when sort is invalid' do
let(:params) { { order_by: 'created_at', sort: 'invalid_sort' } }
it 'sorts as created_at: :desc' do
is_expected.to eq(jobs.sort_by { |p| -p.user.id })
end
end
end
context 'when order_by is invalid' do
let(:params) { { order_by: 'invalid_column', sort: 'asc' } }
let!(:jobs) { Array.new(2) { create(:ci_build, runner: runner, project: project, user: create(:user)) } }
it 'sorts as id: :asc' do
is_expected.to eq(jobs.sort_by { |p| p.id })
end
end
context 'when both are nil' do
let(:params) { { order_by: nil, sort: nil } }
let!(:jobs) { Array.new(2) { create(:ci_build, runner: runner, project: project, user: create(:user)) } }
it 'sorts as id: :desc' do
is_expected.to eq(jobs.sort_by { |p| -p.id })
end
end
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment