Skip to content

Commit

Permalink
Temp
Browse files Browse the repository at this point in the history
  • Loading branch information
yasuflatland-lf committed Jul 16, 2024
1 parent 3424e11 commit 80f4391
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 56 deletions.
11 changes: 11 additions & 0 deletions backend/graph/schema.resolvers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package graph

import (
"backend/pkg/middlewares"
"bytes"
"context"
"encoding/json"
Expand Down Expand Up @@ -60,6 +61,16 @@ func setupEchoServer(db *gorm.DB) *echo.Echo {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Store the database connection in Echo's context
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set(middlewares.DbContext, db)
return next(c)
}
})

// Set Transaction Middleware
e.Use(middlewares.TransactionMiddleware(db))

e.GET("/", func(c echo.Context) error {
playground.Handler("GraphQL playground", "/query").ServeHTTP(c.Response(), c.Request())
Expand Down
41 changes: 31 additions & 10 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package main
import (
"backend/graph"
"backend/pkg/config"
"backend/pkg/middlewares"
"backend/pkg/repository"
"gorm.io/gorm"
"log"
"net/http"
"strconv"
Expand All @@ -20,10 +22,6 @@ var migrationFilePath = "./db/migrations"

func main() {

e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Initialize the database
dbConfig := repository.DBConfig{
Host: config.Cfg.PGHost,
Expand All @@ -36,6 +34,30 @@ func main() {
}
db := repository.InitializeDatabase(dbConfig)

router := NewRouter(db)

router.Logger.Fatal(router.Start(":" + strconv.Itoa(config.Cfg.Port)))

log.Printf("connect to http://localhost:%d/ for GraphQL playground", config.Cfg.Port)
}

func NewRouter(db *gorm.DB) *echo.Echo {

e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Store the database connection in Echo's context
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set(middlewares.DbContext, db)
return next(c)
}
})

// Set Transaction Middleware
e.Use(middlewares.TransactionMiddleware())

// Create a new resolver with the database connection
resolver := &graph.Resolver{
DB: db,
Expand All @@ -59,15 +81,14 @@ func main() {
return nil
})

e.GET("/health", func(c echo.Context) error {
return c.String(http.StatusOK, "OK")
})

e.POST("/query", func(c echo.Context) error {
srv.ServeHTTP(c.Response(), c.Request())
return nil
})

err := e.Start(":" + strconv.Itoa(config.Cfg.Port))
if err != nil {
log.Fatalln(err)
}

log.Printf("connect to http://localhost:%d/ for GraphQL playground", config.Cfg.Port)
return e
}
63 changes: 17 additions & 46 deletions backend/main_test.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
package main

import (
"backend/graph"
"backend/pkg/config"
"backend/testutils"
"context"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4/middleware"
"net/http"
"net/http/httptest"
"testing"

"backend/pkg/config"
"backend/testutils"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)

func TestMainSmoke(t *testing.T) {
t.Parallel()
func setupTestServer(t *testing.T) (*httptest.Server, func()) {
t.Helper()

ctx := context.Background()
user := "test"
Expand All @@ -32,7 +24,6 @@ func TestMainSmoke(t *testing.T) {
if err != nil {
t.Fatalf("Failed to set up test database: %+v", err)
}
defer cleanup(migrationFilePath)

// Run migrations
if err := pg.RunGooseMigrationsUp(migrationFilePath); err != nil {
Expand All @@ -48,45 +39,25 @@ func TestMainSmoke(t *testing.T) {
config.Cfg.PGSSLMode = "disable"
config.Cfg.Port = 8080

// Initialize Echo
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Create a new resolver with the database connection
resolver := &graph.Resolver{
DB: pg.GetDB(),
}

srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: resolver}))
// Initialize the Echo router using the NewRouter function
e := NewRouter(pg.GetDB())

// Setup WebSocket for subscriptions
srv.AddTransport(&transport.Websocket{
Upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
})
ts := httptest.NewServer(e)

e.GET("/", func(c echo.Context) error {
playground.Handler("GraphQL playground", "/query").ServeHTTP(c.Response(), c.Request())
return nil
})
return ts, func() {
ts.Close()
cleanup(migrationFilePath)
}
}

e.POST("/query", func(c echo.Context) error {
srv.ServeHTTP(c.Response(), c.Request())
return nil
})
func TestMainSmoke(t *testing.T) {
t.Parallel()

// Create a test server
ts := httptest.NewServer(e)
defer ts.Close()
ts, cleanup := setupTestServer(t)
defer cleanup()

// Make a simple GET request to the playground
res, err := http.Get(ts.URL)
res, err := http.Get(ts.URL + "/")
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
}
71 changes: 71 additions & 0 deletions backend/pkg/middlewares/transaction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package middlewares

import (
"encoding/json"
"github.com/labstack/echo/v4"
"golang.org/x/net/context"
"gorm.io/gorm"
"net/http"
"strings"
)

var DbContext = "db"
var TxContext = "tx"

type GraphQLRequest struct {
Query string `json:"query"`
}

func TransactionMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
db, ok := c.Get(DbContext).(*gorm.DB)
if !ok {
return echo.NewHTTPError(http.StatusInternalServerError, "Database connection not found")
}

var gqlReq GraphQLRequest
if err := json.NewDecoder(c.Request().Body).Decode(&gqlReq); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid request payload")
}

// Check if the operation is a mutation
if strings.HasPrefix(strings.TrimSpace(gqlReq.Query), "mutation") {
tx := db.Begin()
if tx.Error != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to start transaction")
}

defer func() {
if r := recover(); r != nil {
tx.Rollback()
panic(r)
} else if c.Response().Status >= http.StatusBadRequest {
if err := tx.Rollback().Error; err != nil {
c.Logger().Error("Failed to rollback transaction: ", err)
}
} else {
if err := tx.Commit().Error; err != nil {
c.Logger().Error("Failed to commit transaction: ", err)
}
}
}()

ctx := context.WithValue(c.Request().Context(), TxContext, tx)
c.SetRequest(c.Request().WithContext(ctx))
}

return next(c)
}
}
}

// GetDBFromContext retrieves the GORM DB transaction from the context
func GetDBFromContext(ctx context.Context) *gorm.DB {
tx, _ := ctx.Value(TxContext).(*gorm.DB)
if tx != nil {
return tx
}
// Fallback to the main DB connection if no transaction is found
return ctx.Value(DbContext).(*gorm.DB)
}

0 comments on commit 80f4391

Please sign in to comment.