oc-lib/dbs/dbs.go

106 lines
1.5 KiB
Go
Raw Normal View History

2024-07-18 11:51:12 +02:00
package dbs
import (
2024-08-01 09:13:10 +02:00
"fmt"
"strings"
2024-07-18 11:51:12 +02:00
"go.mongodb.org/mongo-driver/bson"
)
2024-08-01 09:13:10 +02:00
type Operator int
const (
LIKE Operator = iota
EXISTS
IN
GTE
LTE
LT
GT
EQUAL
)
var str = [...]string{
"like",
"exists",
"in",
"gte",
"lte",
"lt",
"gt",
"equal",
}
func (m Operator) String() string {
return str[m]
}
func (m Operator) ToMongoOperator() string {
switch m {
case LIKE:
return "$regex"
case EXISTS:
return "$exists"
case IN:
return "$in"
case GTE:
return "$gte"
case GT:
return "$gt"
case LTE:
return "$lte"
case LT:
return "$lt"
case EQUAL:
return "$match"
default:
return "$regex"
}
}
func StringToOperator(s string) Operator {
for i, v := range str {
if v == s {
return Operator(i)
}
}
return LIKE
}
func ToValueOperator(operator Operator, value interface{}) interface{} {
if strings.TrimSpace(fmt.Sprintf("%v", value)) == "*" {
value = ""
}
if operator == LIKE {
return "(?i).*" + strings.TrimSpace(fmt.Sprintf("%v", value)) + ".*"
}
return value
}
type Filters struct {
And map[string]Filter `json:"and"`
Or map[string]Filter `json:"or"`
}
type Filter struct {
Operator string `json:"operator,omitempty"`
Value interface{} `json:"value,omitempty"`
}
2024-07-18 11:51:12 +02:00
type Input = map[string]interface{}
func InputToBson(i Input, isUpdate bool) bson.D {
input := bson.D{}
for k, v := range i {
if k == "id" {
input = append(input, bson.E{Key: "_id", Value: v})
} else {
input = append(input, bson.E{Key: k, Value: v})
}
}
if isUpdate {
return bson.D{{Key: "$set", Value: input}}
}
return input
}