leaf/filter.go
2024-01-07 08:40:41 +03:00

85 lines
2.0 KiB
Go

package leaf
var (
FilterAll = FilterDocument{}
)
const (
OperatorEq Operator = "$eq"
OperatorNe Operator = "$ne"
OperatorGt Operator = "$gt"
OperatorGte Operator = "$gte"
OperatorLt Operator = "$lt"
OperatorLte Operator = "$lte"
OperatorIn Operator = "$in"
OperatorNin Operator = "$nin"
OperatorExists Operator = "$exists"
OperatorRegex Operator = "$regex"
)
type M map[Operator]any
type Operator string
type FilterDocument map[string]M
func Eq[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorEq, value)
}
func Ne[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorNe, value)
}
func Gt[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorGt, value)
}
func Gte[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorGte, value)
}
func Lt[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorLt, value)
}
func Lte[T any](field string, value T) FilterDocument {
return createSelector(field, OperatorLte, value)
}
func In[T any](field string, value []T) FilterDocument {
return createSelector(field, OperatorIn, value)
}
func Nin[T any](field string, value []T) FilterDocument {
return createSelector(field, OperatorNin, value)
}
func Exists(field string, value bool) FilterDocument {
return createSelector(field, OperatorExists, value)
}
func Regex(field string, value string) FilterDocument {
return createSelector(field, OperatorRegex, value)
}
func createSelector(field string, operator Operator, value any) FilterDocument {
return FilterDocument{field: M{operator: value}}
}
func Filter(docs ...FilterDocument) FilterDocument {
query := FilterDocument{}
for _, doc := range docs {
for field, operators := range doc {
if _, ok := query[field]; !ok {
query[field] = operators
continue
}
for op, value := range operators {
query[field][op] = value
}
}
}
return query
}