Reputation: 1492
We have MVC application written in go
lang
There are 2 endpoint that looks to query database to get all relevant users.
/get_paginate_users - > Query Database with paginate endpoint
/get_users -> [1, 2] -> Query Database with given ID.
To the sake of achieving generic functionality I'm passing the Driver options as the parameters to models function.
// controller.go
// # /get_paginate_users
models.FindUsers(bson.M{}, options.Find().SetLimit(limit))
// bson.M {} and options.Find() are driver specific argument (in our case mongodb).
// controller.go
// # /get_users
models.FindUsers(bson.M{user_ids: bson.M{"$in": user_ids}}, nil)
This where I'm having a discussion with my colleague, He is of the opinion that database related stuff like bson.M
should only the part model. (Since In future if the database is changes it would require change in multiple places)
But doing so result in non generic functions.
What is ideal thing to do over here?, Having to achieve generic function or have model deal with all the driver data type?
Upvotes: 0
Views: 49
Reputation: 564
This sounds like a clear cut example of the Single responsibility Principe
The Controller shouldn't bother with the implementation details of the database you are using. If you were to switch to another DB, only the DB logic should change. The controller should not.
You might want to take a look at the Hexagonal Architecture. Though that might be overkill.
Ideally you would hide the implementation details of the database behind an interface. e.g.:
type UserRepository interface {
FindUser(ctx context.Content, id int) User, error
FindUsersByString(ctx context.Context, s string) User, error
// etc...
}
Which you can them implement with MongoDB, or another DB. The Controller should then have a member userRepo UserRepo
Upvotes: 2