-
Notifications
You must be signed in to change notification settings - Fork 2
/
convert.go
60 lines (51 loc) · 1.65 KB
/
convert.go
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
package mgs
import (
"reflect"
)
// Convert converts the criteria value to a MongoDB query
func Convert(criteria SearchCriteria, qh *QueryHandler) map[string]interface{} {
value := ParseValue(criteria.Value, qh, criteria.Caster)
filter := make(map[string]interface{})
switch criteria.Operation {
case EQUAL:
key := reflect.ValueOf(value).Kind()
if key == reflect.Slice {
filter[criteria.Key] = buildMongoQuery("$in", value)
} else if key == reflect.Struct {
filter[criteria.Key] = buildRegexOperation(value)
} else {
filter[criteria.Key] = value
}
case NOT_EQUAL:
key := reflect.ValueOf(value).Kind()
if key == reflect.Slice {
filter[criteria.Key] = buildMongoQuery("$nin", value)
} else if key == reflect.Struct {
filter[criteria.Key] = buildMongoQuery("$not", buildRegexOperation(value))
} else {
filter[criteria.Key] = buildMongoQuery("$ne", value)
}
case GREATER_THAN:
filter[criteria.Key] = buildMongoQuery("$gt", value)
case GREATER_THAN_EQUAL:
filter[criteria.Key] = buildMongoQuery("$gte", value)
case LESS_THAN:
filter[criteria.Key] = buildMongoQuery("$lt", value)
case LESS_THAN_EQUAL:
filter[criteria.Key] = buildMongoQuery("$lte", value)
case EXISTS:
filter[criteria.Key] = buildMongoQuery("$exists", !criteria.Prefix)
}
return filter
}
func buildMongoQuery(operator string, value interface{}) map[string]interface{} {
query := make(map[string]interface{})
query[operator] = value
return query
}
func buildRegexOperation(value interface{}) map[string]interface{} {
regex := make(map[string]interface{})
regex["$regex"] = value.(Regex).Pattern
regex["$options"] = value.(Regex).Option
return regex
}