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.
46 lines
929 B
46 lines
929 B
6 years ago
|
package base
|
||
|
|
||
|
import (
|
||
|
"github.com/mainnika/mongox-go-driver/mongox"
|
||
|
"github.com/mainnika/mongox-go-driver/mongox/errors"
|
||
|
"github.com/mongodb/mongo-go-driver/bson/primitive"
|
||
|
)
|
||
|
|
||
|
// GetID returns source document id
|
||
|
func GetID(source interface{}) (id interface{}) {
|
||
|
|
||
|
switch doc := source.(type) {
|
||
|
case mongox.BaseObjectID:
|
||
|
return getObjectIdOrGenerate(doc)
|
||
|
case mongox.BaseString:
|
||
|
return getStringIdOrPanic(doc)
|
||
|
default:
|
||
|
panic(errors.Malformedf("source contains malformed document, %v", source))
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func getObjectIdOrGenerate(source mongox.BaseObjectID) (id primitive.ObjectID) {
|
||
|
|
||
|
id = source.GetID()
|
||
|
if id != primitive.NilObjectID {
|
||
|
return id
|
||
|
}
|
||
|
|
||
|
id = primitive.NewObjectID()
|
||
|
source.SetID(id)
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func getStringIdOrPanic(source mongox.BaseString) (id string) {
|
||
|
|
||
|
id = source.GetID()
|
||
|
if id != "" {
|
||
|
return id
|
||
|
}
|
||
|
|
||
|
panic(errors.Malformedf("victim contains malformed document, %v", source))
|
||
|
}
|