diff --git a/mongoext/registry.go b/mongoext/registry.go new file mode 100644 index 0000000..982102f --- /dev/null +++ b/mongoext/registry.go @@ -0,0 +1,31 @@ +package mongoext + +import ( + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "gogs.mikescher.com/BlackForestBytes/goext/rfctime" + "reflect" +) + +func CreateGoExtBsonRegistry() *bsoncodec.Registry { + var primitiveCodecs bson.PrimitiveCodecs + + rb := bsoncodec.NewRegistryBuilder() + bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) + bsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) + + rb.RegisterTypeDecoder(reflect.TypeOf(rfctime.RFC3339Time{}), rfctime.RFC3339Time{}) + + primitiveCodecs.RegisterPrimitiveCodecs(rb) + + return rb.Build() +} + +func encodeRFC3339Time(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) { + +} + +func decodeRFC3339Time(ec bsoncodec.EncodeContext, vr bsonrw.ValueReader, val reflect.Value) { + +} diff --git a/rfctime/rfc3339.go b/rfctime/rfc3339.go index aea8e4f..d89419b 100644 --- a/rfctime/rfc3339.go +++ b/rfctime/rfc3339.go @@ -5,7 +5,10 @@ import ( "errors" "fmt" "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/bson/bsontype" + "reflect" "time" ) @@ -86,6 +89,32 @@ func (t RFC3339Time) MarshalBSONValue() (bsontype.Type, []byte, error) { return bson.MarshalValue(time.Time(t)) } +func (t RFC3339Time) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if val.Kind() == reflect.Ptr && val.IsNil() { + if !val.CanSet() { + return errors.New("ValueUnmarshalerDecodeValue") + } + val.Set(reflect.New(val.Type().Elem())) + } + + tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + if err != nil { + return err + } + + if val.Kind() == reflect.Ptr && len(src) == 0 { + val.Set(reflect.Zero(val.Type())) + return nil + } + + err = t.UnmarshalBSONValue(tp, src) + if err != nil { + return err + } + + return nil +} + func (t RFC3339Time) Serialize() string { return t.Time().Format(t.FormatStr()) }