Reputation: 126
My main problem is how to inject loggers into the functions attached to the models? So for example, if we have a User model
type User struct {
id string `json:"id" bson:"id"`
name string `json:"name" bson:"name"`
}
and then let's we have a function attached to it
func (user *User) Save() {
...
}
Now what I want to do with this is to create an struct that has logger and other information attached with it
type UserStruct struct {
logger ...
dbConn ...
...
}
Now my problem is that if I inject this into the controllers then they would have access to the objects that they don't need. I can't find a nice way to isolate these from the controller and only inject the functions on the models into the controller.
Upvotes: 0
Views: 115
Reputation: 34282
Rather than implementing an active record pattern in Go, I'd suggest using a persistence layer that receives all those data objects like User
. For example:
type Persistence struct {
logger logging.Logger
conn *mongo.Client
// ...
}
func NewPersistence(...) (*Persistence, error) {
// connect to mongo etc
return &Persistence{...}, nil
}
func (p *Persistence) SaveUser(user *User) error {
// ...
}
func (p *Persistence) FindUserByName(username string) (*User, error) {
// ...
}
Upvotes: 3