Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add a mongo registry option to convert type easier. #3780

Merged
merged 15 commits into from
Mar 2, 2024

Conversation

POABOB
Copy link
Contributor

@POABOB POABOB commented Dec 11, 2023

Issue #3734.

If users want to convert their custom type to a MongoDB primitive type, they have to define a WithRegistry() function and set up the Encoder/Decoder.

mongo/mongo.go

package mongo

// ...

func WithRegistry(registry *bsoncodec.Registry) mon.Option {
	return func(opts *mopt.ClientOptions) {
		opts.SetRegistry(registry)
	}
}

// Mongo type Encoder/Decoder
var MongoDecimalEncoder bsoncodec.ValueEncoderFunc = func(ect bsoncodec.EncodeContext, w bsonrw.ValueWriter, value reflect.Value) error {...}
var MongoDecimalDecoder bsoncodec.ValueDecoderFunc = func(ect bsoncodec.DecodeContext, r bsonrw.ValueReader, value reflect.Value) error {...}
var MongoDateTimeEncoder bsoncodec.ValueEncoderFunc = func(ect bsoncodec.EncodeContext, w bsonrw.ValueWriter, value reflect.Value) error {...}
var MongoDateTimeDecoder bsoncodec.ValueDecoderFunc = func(ect bsoncodec.DecodeContext, r bsonrw.ValueReader, value reflect.Value) error {...}

And RegisterTypeEncoder and RegisterTypeDecoder like below:

main.go

package main

// ...

type User struct {
	ID        primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
	Name      string             `bson:"name,omitempty" json:"name,omitempty"`
	Money     decimal.Decimal    `bson:"money,omitempty" json:"money,omitempty"`
	CreatedAt time.Time          `bson:"created_at,omitempty" json:"created_at,omitempty"`
}

func main() {
	// ...
	registry := bson.NewRegistry()
	registry.RegisterTypeEncoder(reflect.TypeOf(decimal.Decimal{}), mongo.MongoDecimalEncoder)
	registry.RegisterTypeDecoder(reflect.TypeOf(decimal.Decimal{}), mongo.MongoDecimalDecoder)
	registry.RegisterTypeEncoder(reflect.TypeOf(time.Time{}), mongo.MongoDateTimeEncoder)
	registry.RegisterTypeDecoder(reflect.TypeOf(time.Time{}), mongo.MongoDateTimeDecoder)
	opts := mongo.WithRegistry(registry)
	conn := mon.MustNewModel("mongodb://localhost:27017", "test", "collection", opts)

	// find
	var users []User
	err := conn.Find(ctx, &users, bson.D{{}})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(users)
}

In order to make this easier, I added a WithRegister() function so that users don't need to implement it themselves. I also used a RegisterType struct to store custom types and their respective Encoder/Decoder functions.
In this feature, users only need to define the Encoder/Decoder and use WithRegistry().

mongo/mongo.go

package mongo

// ...

// No more use
// func WithRegistry(registry *bsoncodec.Registry) mon.Option {
// 	return func(opts *mopt.ClientOptions) {
// 		opts.SetRegistry(registry)
// 	}
// }

// Mongo type Encoder/Decoder
var MongoDecimalEncoder bsoncodec.ValueEncoderFunc = func(ect bsoncodec.EncodeContext, w bsonrw.ValueWriter, value reflect.Value) error {...}
var MongoDecimalDecoder bsoncodec.ValueDecoderFunc = func(ect bsoncodec.DecodeContext, r bsonrw.ValueReader, value reflect.Value) error {...}
var MongoDateTimeEncoder bsoncodec.ValueEncoderFunc = func(ect bsoncodec.EncodeContext, w bsonrw.ValueWriter, value reflect.Value) error {...}
var MongoDateTimeDecoder bsoncodec.ValueDecoderFunc = func(ect bsoncodec.DecodeContext, r bsonrw.ValueReader, value reflect.Value) error {...}

main.go

package main

// ...

type User struct {
	ID        primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
	Name      string             `bson:"name,omitempty" json:"name,omitempty"`
	Money     decimal.Decimal    `bson:"money,omitempty" json:"money,omitempty"`
	CreatedAt time.Time          `bson:"created_at,omitempty" json:"created_at,omitempty"`
}

func main() {
	// ...
	registerType := []mon.RegisterType{
		{
			ValueType: reflect.TypeOf(decimal.Decimal{}),
			Encoder:   mongo.MongoDecimalEncoder,
			Decoder:   mongo.MongoDecimalDecoder,
		},
		{
			ValueType: reflect.TypeOf(time.Time{}),
			Encoder:   mongo.MongoDateTimeEncoder,
			Decoder:   mongo.MongoDateTimeDecoder,
		},
	}
	opts := mon.WithRegistry(registerType...)
	conn := mon.MustNewModel("mongodb://localhost:27017", "test", "collection", opts)
	
	// find
	var users []User
	err := conn.Find(ctx, &users, bson.D{{}})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(users)
}

Copy link

codecov bot commented Dec 16, 2023

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 94.72%. Comparing base (45be48a) to head (69a4428).

Additional details and impacted files
Files Coverage Δ
core/stores/mon/options.go 100.00% <100.00%> (ø)

... and 1 file with indirect coverage changes

@kevwan
Copy link
Contributor

kevwan commented Dec 16, 2023

Thanks for your PR!

I recommend not to import decimal package only because of unit test.

@POABOB
Copy link
Contributor Author

POABOB commented Dec 18, 2023

OK, done!

@POABOB
Copy link
Contributor Author

POABOB commented Dec 30, 2023

@kevwan Do I need to do anything extra?

Copy link
Contributor

@kevwan kevwan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@kevwan kevwan added this pull request to the merge queue Mar 2, 2024
Merged via the queue into zeromicro:master with commit be7f939 Mar 2, 2024
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants