~netlandish/gobwebs

1e14c8ae92d7223768529a57bcf0f850cf8b2c7e — Peter Sanchez 1 year, 9 months ago 3f4e458
Adding DBTransactionMiddleware
2 files changed, 25 insertions(+), 5 deletions(-)

A database/middleware.go
M server/server.go
A database/middleware.go => database/middleware.go +19 -0
@@ 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
	}
}

M server/server.go => server/server.go +6 -5
@@ 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)
		}
	})