Compatible with both bolt and mongo, wewt

This commit is contained in:
Bel LaPointe
2020-07-23 20:01:09 -06:00
parent 99885da94f
commit 4416a7e4b3
3 changed files with 57 additions and 2 deletions

View File

@@ -8,6 +8,7 @@ import (
"local/dndex/storage/entity"
"os"
"regexp"
"strings"
"github.com/boltdb/bolt"
"go.mongodb.org/mongo-driver/bson"
@@ -262,6 +263,8 @@ func apply(doc bson.M, operator interface{}) (bson.M, error) {
switch k {
case "$set":
op = applySet
case "$unset":
op = applyUnset
default:
return nil, errors.New("cannot apply operation " + k)
}
@@ -273,6 +276,38 @@ func apply(doc bson.M, operator interface{}) (bson.M, error) {
return doc, nil
}
func applyUnset(doc, operator bson.M) (bson.M, error) {
for k := range operator {
if k == entity.Name {
return nil, errModifiedReserved
}
nesting := strings.Split(k, ".")
if len(nesting) > 1 {
mInterface, ok := doc[nesting[0]]
if !ok {
return nil, fmt.Errorf("path does not exist: %s (%s): %+v", k, nesting[0], doc)
}
m, ok := mInterface.(map[string]interface{})
if !ok {
pm, pmok := mInterface.(primitive.M)
m = map[string]interface{}(pm)
ok = pmok
}
if !ok {
return nil, fmt.Errorf("subpath cannot be followed for non object: %s (%s): %+v (%T)", k, nesting[0], mInterface, mInterface)
}
subdoc, err := applyUnset(bson.M(m), bson.M{strings.Join(nesting[1:], "."): ""})
if err != nil {
return nil, err
}
operator[k] = subdoc
} else {
delete(doc, k)
}
}
return doc, nil
}
func applySet(doc, operator bson.M) (bson.M, error) {
for k, v := range operator {
if k == entity.Name {