From 1e14c8ae92d7223768529a57bcf0f850cf8b2c7e Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Tue, 14 Feb 2023 12:27:35 -0600 Subject: [PATCH] Adding DBTransactionMiddleware --- database/middleware.go | 19 +++++++++++++++++++ server/server.go | 11 ++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 database/middleware.go diff --git a/database/middleware.go b/database/middleware.go new file mode 100644 index 0000000..72287ce --- /dev/null +++ b/database/middleware.go @@ -0,0 +1,19 @@ +package database + +import ( + "github.com/labstack/echo/v4" +) + +// DBTransactionMiddleware will commit a transaction at the end of a request cycle +// Should be placed as high up in the cycle as possible. +func DBTransactionMiddleware(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + res := next(c) + db := DBFromContext(c.Request().Context()) + db.EnableCommit() + if err := db.CommitTx(); err != nil { + return err + } + return res + } +} diff --git a/server/server.go b/server/server.go index ea6518e..a361034 100644 --- a/server/server.go +++ b/server/server.go @@ -67,7 +67,6 @@ type Server struct { type Context struct { echo.Context Server *Server - DB database.DBI User gobwebs.User } @@ -285,13 +284,15 @@ func (s *Server) WithDefaultMiddleware() *Server { if s.Session == nil { panic(fmt.Errorf("You must call Initialize before WithDefaultMiddleware")) } - //s.e.Pre(middleware.RemoveTrailingSlashWithConfig(middleware.TrailingSlashConfig{ - // RedirectCode: http.StatusMovedPermanently, - //})) // Set custom context s.e.Use(func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { - ctx := &Context{Context: c, Server: s, DB: database.NewDB(s.DB)} + ctx := &Context{Context: c, Server: s} + c.SetRequest( + c.Request().WithContext( + database.Context(c.Request().Context(), database.NewDB(s.DB)), + ), + ) return next(ctx) } }) -- 2.45.2