-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathquery.dart
74 lines (50 loc) · 2.17 KB
/
query.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
part of appwrite;
// regex to extract method name and params
final _methodAndParamsRegEx = RegExp(r'(\w+)\((.*)\)');
class Query {
Query._(this.method, this.params);
static equal(String attribute, dynamic value) =>
_addQuery(attribute, 'equal', value);
static notEqual(String attribute, dynamic value) =>
_addQuery(attribute, 'notEqual', value);
static lessThan(String attribute, dynamic value) =>
_addQuery(attribute, 'lessThan', value);
static lessThanEqual(String attribute, dynamic value) =>
_addQuery(attribute, 'lessThanEqual', value);
static greaterThan(String attribute, dynamic value) =>
_addQuery(attribute, 'greaterThan', value);
static greaterThanEqual(String attribute, dynamic value) =>
_addQuery(attribute, 'greaterThanEqual', value);
static search(String attribute, String value) =>
_addQuery(attribute, 'search', value);
static String orderAsc(String attribute) => 'orderAsc("$attribute")';
static String orderDesc(String attribute) => 'orderDesc("$attribute")';
static String cursorBefore(String id) => 'cursorBefore("$id")';
static String cursorAfter(String id) => 'cursorAfter("$id")';
static String limit(int limit) => 'limit($limit)';
static String offset(int offset) => 'offset($offset)';
static String _addQuery(String attribute, String method, dynamic value) => (value
is List)
? '$method("$attribute", [${value.map((item) => parseValues(item)).join(",")}])'
: '$method("$attribute", [${parseValues(value)}])';
static String parseValues(dynamic value) =>
(value is String) ? '"$value"' : '$value';
String method;
List<dynamic> params;
factory Query.parse(String query) {
if (!query.contains('(') || !query.contains(')')) {
throw Exception('Invalid query');
}
final matches = _methodAndParamsRegEx.firstMatch(query);
if (matches == null || matches.groupCount < 2) {
throw Exception('Invalid query');
}
final method = matches.group(1)!;
try {
final params = jsonDecode('[' + matches.group(2)! + ']') as List<dynamic>;
return Query._(method, params);
} catch (e) {
throw Exception('Invalid query');
}
}
}