假设我有一个非常简单的存储库接口,它只从目标数据库读取:
type UserRepository interface {
read(ctx context.Context, id WHAT_TYPE_I_SHOULD_USE_HERE) models.User
}
注意:请注意,在 id 参数中,我不知道用户作为 id 类型是什么,因为 id 在MongoDB基于ObjectId模式的数据库中它可能是一个UUID字段。如果有帮助,我的主数据库是 MongoDB,但我可能会切换到基于模式的数据库。
现在我有一个附加到它的MongoDBRepository结构:read()
type MongoDBRepository struct {
}
func (mo MongoDBRepository) read(ctx context.Context, id primitive.ObjectID) {
fmt.Printf("read user %s from MongoDB", id)
}
我有一个连接到 MongoDB 的方法:
func ConnectMongoDB() (*mongo.Client, context.CancelFunc) {
client, err := mongo.NewClient(options.Client().ApplyURI(configs.MongoURI()))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
log.Print("Successfully connected to MongoDB!")
return client, cancel
}
现在,随着接口的实现,我们可以为MySQL/PostgreSQL和ConnectMySQL/拥有一个类似的存储库ConnectPostgreSQL。
我遇到的问题是在我的主要功能中我应该如何处理连接到我当前的数据库存储库以及如何在我的控制器中使用它来读取或更新文档/记录?
当我将连接传递给控制器方法时,其类型设置为*mongo.Client如何将其抽象化,以便获取数据库连接的控制器方法未绑定到目标数据库类型?
狐的传说
相关分类