You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mongox-go-driver/mongox/base/getid.go

72 lines
1.4 KiB

package base
import (
"fmt"
4 years ago
"github.com/modern-go/reflect2"
5 years ago
"go.mongodb.org/mongo-driver/bson/primitive"
5 years ago
"github.com/mainnika/mongox-go-driver/v2/mongox"
)
// GetID returns source document id
func GetID(source interface{}) (id interface{}) {
switch doc := source.(type) {
case mongox.OIDBased:
5 years ago
return getObjectIDOrGenerate(doc)
case mongox.StringBased:
5 years ago
return getStringIDOrPanic(doc)
case mongox.JSONBased:
6 years ago
return getObjectOrPanic(doc)
case mongox.InterfaceBased:
return getInterfaceOrPanic(doc)
default:
panic(fmt.Errorf("source contains malformed document, %v", source))
}
}
func getObjectIDOrGenerate(source mongox.OIDBased) (id primitive.ObjectID) {
id = source.GetID()
if id != primitive.NilObjectID {
return id
}
id = primitive.NewObjectID()
source.SetID(id)
return
}
func getStringIDOrPanic(source mongox.StringBased) (id string) {
id = source.GetID()
if id != "" {
return id
}
panic(fmt.Errorf("source contains malformed document, %v", source))
}
6 years ago
func getObjectOrPanic(source mongox.JSONBased) (id primitive.D) {
6 years ago
id = source.GetID()
if id != nil {
return id
}
panic(fmt.Errorf("source contains malformed document, %v", source))
6 years ago
}
func getInterfaceOrPanic(source mongox.InterfaceBased) (id interface{}) {
id = source.GetID()
4 years ago
if !reflect2.IsNil(id) {
return id
}
panic(fmt.Errorf("source contains malformed document, %v", source))
}