假设我有一个非常简单的存储库界面,只从目标数据库读取:
type UserRepository interface {
read(ctx context.Context, id WHAT_TYPE_I_SHOULD_USE_HERE) models.User
}
NOTE:注意,在id参数中,我不知道用户应该使用什么,因为MongoDB
中的id类型是ObjectId
,而在基于模式的数据库中,它可能是UUID
字段.如果有帮助的话,我的主要数据库是MongoDB,但我可能会切换到基于模式的数据库.
现在我有一个MongoDBRepository
struct ,它有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
.我如何将其抽象出来,使我获得DB连接的控制器方法不绑定到目标DB类型?