package ginctx import ( "clapclap/internal/apperr" "clapclap/internal/env" "clapclap/internal/repositories" "sync/atomic" "time" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/gin-gonic/gin" "gorm.io/gorm" ) func UseRepo(r gin.IRouter) { r.Use(func(c *gin.Context) { // Fetch the dynamic DB pointer placed by UseDB middleware for THIS request db, err := GetDB(c, "db") if err == nil { // Create a fresh Repo instance pointing to the current DB repo := &repositories.Repo{} repo.Connect(db) c.Set("repo", repo) } }) } func UseEnvJwtSecret(r gin.IRoutes) gin.IRoutes { secret := env.C.JWT_SECRET r.Use(func(c *gin.Context) { c.Set("server-jwt-secret", secret) c.Next() }) return r } func UseTimestamp(r gin.IRoutes) gin.IRoutes { setTimestamp := func(c *gin.Context) { c.Set("timestamp", time.Now()) c.Next() } r.Use(setTimestamp) return r } func UseAtomic(r gin.IRoutes, key string, atom *atomic.Value) gin.IRoutes { r.Use(func(c *gin.Context) { c.Set(key, atom) c.Next() }) return r } func UseTx(r gin.IRoutes, db *gorm.DB) gin.IRoutes { r.Use(func(c *gin.Context) { tx := db.Begin() if tx.Error != nil { apperr.AbortWithError(c, apperr.NewDatabaseError(tx.Error, "Failed to start database transaction")) return } defer func() { if r := recover(); r != nil { tx.Rollback() panic(r) } }() c.Set("tx", tx) c.Next() if c.IsAborted() { tx.Rollback() } else { tx.Commit() } }) return r } func UseS3(r gin.IRoutes, client *s3.Client, internal *s3.Client) gin.IRoutes { r.Use(func(c *gin.Context) { c.Set("s3", client) c.Set("s3-internal", internal) }) return r }