I'm using fx + mysql + gin and I need some help to figure out how to turn a database connection scoped.
Let's go through this points:
The project is a rest api and I need to know how can I request a connection during a request and use the same connection during the entire request, then when the request is done I need to close it.
The main point is if I use 2 different repositories in the same request I get 2 diferent connections and this doesn't make sense since the cost of opening a connection is high! I should be able to open a new connection "OnRequestBegin" and release "OnRequestEnd". I worked with some injectors before for other languages but I didn't find anything related to it for FX.
Am I losing something? Does anyone know how to solve this?
I had a similar problem and couldn't find a solution... So I created my own...
For each request I start a new Fx instance to simulate a scope.
type Scope struct {
request *http.Request
}
func NewScope(c *gin.Context) *Scope {
return &Scope{
request: c.Request,
}
}
func (f *Scope) NewRepository() repository.Repository {
return ...
}
func NewGinHandler(log *zap.Logger) http.Handler {
r := gin.New()
r.GET("/todos", func(c *gin.Context) {
scope := NewScope(c)
fx.New(
// register repository constructor
fx.Provide(scope.NewRepository),
// actual request handler with access to repository
fx.Invoke(func(repository repository.Repository) {
todos := repository.FindAll()
c.JSON(200, todos)
}),
)
})
return r
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With