Adding order by to list runner jobs api.

This commit is contained in:
sujay patel 2019-06-13 01:33:21 +05:30 committed by sujay
parent 2fec78ead4
commit b71250ca0f
4 changed files with 65 additions and 1 deletions

View file

@ -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

View file

@ -0,0 +1,5 @@
---
title: 51794-add-order-by-to-list-runner-jobs-api
merge_request:
author: Sujay Patel
type: added

View file

@ -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"

View file

@ -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