Skip to content

Commit

Permalink
Refactor writher
Browse files Browse the repository at this point in the history
  • Loading branch information
minhduc140583 committed Jun 16, 2024
1 parent 742486a commit 10760aa
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
24 changes: 24 additions & 0 deletions writer/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package writer

import (
"reflect"
"strings"
)

func FindIdField(modelType reflect.Type) int {
return FindField(modelType, "_id")
}
func FindField(modelType reflect.Type, bsonName string) int {
numField := modelType.NumField()
for i := 0; i < numField; i++ {
field := modelType.Field(i)
bsonTag := field.Tag.Get("bson")
tags := strings.Split(bsonTag, ",")
for _, tag := range tags {
if strings.TrimSpace(tag) == bsonName {
return i
}
}
}
return -1
}
4 changes: 1 addition & 3 deletions writer/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"reflect"

mgo "github.com/core-go/mongo"
)

type Updater[T any] struct {
Expand All @@ -28,7 +26,7 @@ func NewUpdaterWithId[T any](database *mongo.Database, collectionName string, op
modelType = modelType.Elem()
isPointer = true
}
index, _, _ := mgo.FindIdField(modelType)
index := FindIdField(modelType)
collection := database.Collection(collectionName)
return &Updater[T]{collection: collection, idIndex: index, Map: mp, isPointer: isPointer}
}
Expand Down
4 changes: 1 addition & 3 deletions writer/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"

mgo "github.com/core-go/mongo"
)

type Writer[T any] struct {
Expand All @@ -29,7 +27,7 @@ func NewWriter[T any](database *mongo.Database, collectionName string, options .
modelType = modelType.Elem()
isPointer = true
}
index, _, _ := mgo.FindIdField(modelType)
index := FindIdField(modelType)
collection := database.Collection(collectionName)
return &Writer[T]{collection: collection, idIndex: index, Map: mp, isPointer: isPointer}
}
Expand Down

0 comments on commit 10760aa

Please sign in to comment.