Support descending ordering in generic API filter (closes #1167)

This commit is contained in:
Bernd Bestel 2020-12-09 21:04:04 +01:00
parent 19802bc122
commit fda8411ab3
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
3 changed files with 20 additions and 3 deletions

View File

@ -188,7 +188,7 @@
- `/chores` - `/chores`
- `/batteries` - `/batteries`
- There are 4 new (optional) query parameters to utilize that - There are 4 new (optional) query parameters to utilize that
- `order` The field to order by - `order` The field to order by (use the separator `:` to specify the sort order - `asc` or `desc`, defaults to `asc` when omitted)
- `limit` The maximum number of objects to return - `limit` The maximum number of objects to return
- `offset` The number of objects to skip - `offset` The number of objects to skip
- `query[]` An array of conditions, each of them is a string in the form of `<field><condition><value>`, where - `query[]` An array of conditions, each of them is a string in the form of `<field><condition><value>`, where

View File

@ -47,14 +47,31 @@ class BaseApiController extends BaseController
{ {
$data = $this->filter($data, $query['query']); $data = $this->filter($data, $query['query']);
} }
if (isset($query['limit'])) if (isset($query['limit']))
{ {
$data = $data->limit(intval($query['limit']), intval($query['offset'] ?? 0)); $data = $data->limit(intval($query['limit']), intval($query['offset'] ?? 0));
} }
if (isset($query['order'])) if (isset($query['order']))
{ {
$data = $data->orderBy($query['order']); $parts = explode(':', $query['order']);
if (count($parts) == 1)
{
$data = $data->orderBy($parts[0]);
} }
else
{
if ($parts[1] != 'asc' && $parts[1] != 'desc')
{
throw new \Exception('Invalid sort order ' . $parts[1]);
}
$data = $data->orderBy($parts[0], $parts[1]);
}
}
return $data; return $data;
} }

View File

@ -5053,7 +5053,7 @@
"in": "query", "in": "query",
"name": "order", "name": "order",
"required": false, "required": false,
"description": "A valid field name by which the response should be ordered", "description": "A valid field name by which the response should be ordered, use the separator `:` to specify the sort order (`asc` or `desc`, defaults to `asc` when omitted)",
"schema": { "schema": {
"type": "string" "type": "string"
} }