TTime/backend/internal/database/middleware.go

35 lines
809 B
Go
Raw Normal View History

package database
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/log"
"github.com/jmoiron/sqlx"
)
// Simple middleware that provides a transaction as a local key "db"
func DbMiddleware(db *sqlx.DB) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
tx := db.MustBegin()
defer func() {
if err := tx.Commit(); err != nil {
if err = tx.Rollback(); err != nil {
log.Error("Failed to rollback transaction: ", err)
}
return
}
}()
var db_iface Database = &Db{tx}
c.Locals("db", &db_iface)
return c.Next()
}
}
// Helper function to get the database from the context, without fiddling with casts
func GetDb(c *fiber.Ctx) Database {
// Dereference a pointer to a local, casted to a pointer to a Database
return *c.Locals("db").(*Database)
}