-
-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
library query; | ||
|
||
export 'package:json_api/src/query/fields.dart'; | ||
export 'package:json_api/src/query/filters.dart'; | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
Inobtenio
Author
Contributor
|
||
export 'package:json_api/src/query/include.dart'; | ||
export 'package:json_api/src/query/page.dart'; | ||
export 'package:json_api/src/query/query_parameters.dart'; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import 'package:json_api/src/query/query_parameters.dart'; | ||
|
||
/// Query parameters defining Filters | ||
/// @see https://jsonapi.org/recommendations/#filtering | ||
class Filters extends QueryParameters { | ||
/// The [filter] argument maps the resource type to a list of filters. | ||
/// | ||
/// Example: | ||
/// ```dart | ||
/// Filters({'articles': ['title', 'body'], 'people': ['name']}).addTo(url); | ||
/// ``` | ||
/// encodes to | ||
/// ``` | ||
/// ?filter[articles]=title,body&filter[people]=name | ||
/// ``` | ||
Filters(Map<String, List<String>> filter) | ||
: _filter = {...filter}, | ||
super(filter.map((k, v) => MapEntry('filter[$k]', v.join(',')))); | ||
|
||
/// Extracts the requested filter from the [uri]. | ||
static Filters fromUri(Uri uri) => Filters(uri.queryParameters | ||
.map((k, v) => MapEntry(_regex.firstMatch(k)?.group(1), v.split(','))) | ||
..removeWhere((k, v) => k == null)); | ||
|
||
List<String> operator [](String key) => _filter[key]; | ||
|
||
static final _regex = RegExp(r'^filter\[(.+)\]$'); | ||
|
||
final Map<String, List<String>> _filter; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import 'package:json_api/src/query/filters.dart'; | ||
import 'package:test/test.dart'; | ||
|
||
void main() { | ||
test('Can decode url', () { | ||
final uri = Uri.parse( | ||
'/articles?include=author&filter%5Barticles%5D=title%2Cbody&filter%5Bpeople%5D=name'); | ||
final filter = Filters.fromUri(uri); | ||
expect(filter['articles'], ['title', 'body']); | ||
expect(filter['people'], ['name']); | ||
}); | ||
|
||
test('Can add to uri', () { | ||
final filter = Filters({ | ||
'articles': ['title', 'body'], | ||
'people': ['name'] | ||
}); | ||
final uri = Uri.parse('/articles'); | ||
|
||
expect(filter.addToUri(uri).toString(), | ||
'/articles?filter%5Barticles%5D=title%2Cbody&filter%5Bpeople%5D=name'); | ||
}); | ||
} |
@Inobtenio I like the idea of this change, would you like to open a PR?