Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FX UBER: How to deal with request scoped lifecycle for database transient connections?

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:

  1. Registered a factory (New) to return a db connection;
  2. My repository struct uses this connection inside its New constructor function;

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?

like image 424
Leandro Curioso Avatar asked Dec 05 '25 18:12

Leandro Curioso


1 Answers

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
}
like image 140
FLUXparticle Avatar answered Dec 08 '25 15:12

FLUXparticle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!