Skip to content

Commit

Permalink
Fix assosiation errors
Browse files Browse the repository at this point in the history
  • Loading branch information
yasuflatland-lf committed Aug 9, 2024
1 parent 9c39d87 commit d903d68
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 90 deletions.
9 changes: 7 additions & 2 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@ jobs:
- name: Install Goose
run: go install github.com/pressly/goose/v3/cmd/goose@latest

# Alternatively, install using go install
- name: Set up gotestfmt
run: go install github.com/gotesttools/gotestfmt/v2/cmd/gotestfmt@latest

- name: Fetch dependant Go modules
run: |-
go get -v -t -d ./...
working-directory: ./backend

- name: Test code
run: |-
go test -v ./...
run: |
set -euo pipefail
go test -json -v ./... 2>&1 | tee /tmp/gotest.log | gotestfmt
working-directory: ./backend
3 changes: 2 additions & 1 deletion backend/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ fmt: ## Format code
test: ## Run tests
printf "${GREEN}Run all tests\n\n${WHITE}"; \
go clean -cache -testcache -i -r; \
go test -race -run=./... -bench=./... ./...; \
go install github.com/gotesttools/gotestfmt/v2/cmd/gotestfmt@latest; \
go test -race -json -v -coverprofile=coverage.txt ./... 2>&1 | tee /tmp/gotest.log | gotestfmt; \
printf "${GREEN}Done\n"; \

.PHONY: init
Expand Down
5 changes: 1 addition & 4 deletions backend/cmd/gqlgenerate/main_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package main

import (
"log"
"os"
"testing"

"github.com/99designs/gqlgen/plugin/modelgen"
Expand All @@ -17,13 +15,12 @@ func TestLoadGraphQLConfig(t *testing.T) {
}

func TestGenerateGraphQLCode(t *testing.T) {
logger := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
cfg, err := loadGraphQLConfig()
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}

err = generateGraphQLCode(cfg, logger)
err = generateGraphQLCode(cfg)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
Expand Down
70 changes: 46 additions & 24 deletions backend/graph/services/card.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,29 @@ func convertToCard(card repository.Card) *model.Card {
}
}

func convertCardConnection(cards []repository.Card, hasPrevPage, hasNextPage bool) *model.CardConnection {
var result model.CardConnection

for _, dbc := range cards {
card := convertToCard(dbc)

// Use the ID directly as it is already of type int64
result.Edges = append(result.Edges, &model.CardEdge{Cursor: card.ID, Node: card})
result.Nodes = append(result.Nodes, card)
}
result.TotalCount = len(cards)

result.PageInfo = &model.PageInfo{}
if result.TotalCount != 0 {
result.PageInfo.StartCursor = &result.Nodes[0].ID
result.PageInfo.EndCursor = &result.Nodes[result.TotalCount-1].ID
}
result.PageInfo.HasPreviousPage = hasPrevPage
result.PageInfo.HasNextPage = hasNextPage

return &result
}

func (s *cardService) GetCardByID(ctx context.Context, id int64) (*model.Card, error) {
var card repository.Card
if err := s.db.WithContext(ctx).First(&card, id).Error; err != nil {
Expand Down Expand Up @@ -167,33 +190,32 @@ func (s *cardService) PaginatedCardsByCardGroup(ctx context.Context, cardGroupID
return nil, err
}

var edges []*model.CardEdge
var nodes []*model.Card
for _, card := range cards {
node := convertToCard(card)
edges = append(edges, &model.CardEdge{
Cursor: card.ID,
Node: node,
})
nodes = append(nodes, node)
}

pageInfo := &model.PageInfo{}
if len(cards) > 0 {
pageInfo.HasNextPage = len(cards) == s.defaultLimit
pageInfo.HasPreviousPage = len(cards) == s.defaultLimit
if len(edges) > 0 {
pageInfo.StartCursor = &edges[0].Cursor
pageInfo.EndCursor = &edges[len(edges)-1].Cursor
var hasNextPage, hasPrevPage bool
var count int64

if len(cards) != 0 {
startCursor, endCursor := cards[0].ID, cards[len(cards)-1].ID

err := s.db.WithContext(ctx).Model(&repository.Card{}).
Where("cardgroup_id = ?", cardGroupID).
Where("id < ?", startCursor).
Count(&count).Error
if err != nil {
return nil, err
}
hasPrevPage = count > 0

err = s.db.WithContext(ctx).Model(&repository.Card{}).
Where("cardgroup_id = ?", cardGroupID).
Where("id > ?", endCursor).
Count(&count).Error
if err != nil {
return nil, err
}
hasNextPage = count > 0
}

return &model.CardConnection{
Edges: edges,
Nodes: nodes,
PageInfo: pageInfo,
TotalCount: len(cards),
}, nil
return convertCardConnection(cards, hasPrevPage, hasNextPage), nil
}

func (s *cardService) GetCardsByIDs(ctx context.Context, ids []int64) ([]*model.Card, error) {
Expand Down
38 changes: 19 additions & 19 deletions backend/graph/services/cardgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@ func convertToCardGroup(cardGroup repository.Cardgroup) *model.CardGroup {
func (s *cardGroupService) GetCardGroupByID(ctx context.Context, id int64) (*model.CardGroup, error) {
var cardGroup repository.Cardgroup
if err := s.db.First(&cardGroup, id).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to get card group by ID", err)
logger.Logger.ErrorContext(ctx, "Failed to get cardgroup by ID", err)
return nil, err
}
return convertToCardGroup(cardGroup), nil
}

func (s *cardGroupService) CreateCardGroup(ctx context.Context, input model.NewCardGroup) (*model.CardGroup, error) {
gormCardGroup := convertToGormCardGroup(input)
result := s.db.WithContext(ctx).Create(gormCardGroup)
result := s.db.WithContext(ctx).Create(&gormCardGroup)
if result.Error != nil {
logger.Logger.ErrorContext(ctx, "Failed to create card group", result.Error)
logger.Logger.ErrorContext(ctx, "Failed to create cardgroup", result.Error)
return nil, result.Error
}
return convertToCardGroup(*gormCardGroup), nil
Expand All @@ -55,7 +55,7 @@ func (s *cardGroupService) CreateCardGroup(ctx context.Context, input model.NewC
func (s *cardGroupService) CardGroups(ctx context.Context) ([]*model.CardGroup, error) {
var cardGroups []repository.Cardgroup
if err := s.db.WithContext(ctx).Find(&cardGroups).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to retrieve card groups", err)
logger.Logger.ErrorContext(ctx, "Failed to retrieve cardgroups", err)
return nil, err
}
var gqlCardGroups []*model.CardGroup
Expand All @@ -68,13 +68,13 @@ func (s *cardGroupService) CardGroups(ctx context.Context) ([]*model.CardGroup,
func (s *cardGroupService) UpdateCardGroup(ctx context.Context, id int64, input model.NewCardGroup) (*model.CardGroup, error) {
var cardGroup repository.Cardgroup
if err := s.db.WithContext(ctx).First(&cardGroup, id).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to find card group for update", err)
logger.Logger.ErrorContext(ctx, "Failed to find cardgroup for update", err)
return nil, err
}
cardGroup.Name = input.Name
cardGroup.Updated = time.Now()
if err := s.db.WithContext(ctx).Save(&cardGroup).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to update card group", err)
logger.Logger.ErrorContext(ctx, "Failed to update cardgroup", err)
return nil, err
}
return convertToCardGroup(cardGroup), nil
Expand All @@ -84,12 +84,12 @@ func (s *cardGroupService) DeleteCardGroup(ctx context.Context, id int64) (*bool
success := false
result := s.db.WithContext(ctx).Delete(&repository.Cardgroup{}, id)
if result.Error != nil {
logger.Logger.ErrorContext(ctx, "Failed to delete card group", result.Error)
logger.Logger.ErrorContext(ctx, "Failed to delete cardgroup", result.Error)
return &success, result.Error
}
if result.RowsAffected == 0 {
err := fmt.Errorf("record not found")
logger.Logger.ErrorContext(ctx, "Card group not found for deletion", err)
logger.Logger.ErrorContext(ctx, "Cardgroup not found for deletion", err)
return &success, err
}
success = true
Expand All @@ -100,15 +100,15 @@ func (s *cardGroupService) AddUserToCardGroup(ctx context.Context, userID int64,
var user repository.User
var cardGroup repository.Cardgroup
if err := s.db.WithContext(ctx).First(&user, userID).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to find user for adding to card group", err)
logger.Logger.ErrorContext(ctx, "Failed to find user for adding to cardgroup", err)
return nil, err
}
if err := s.db.WithContext(ctx).First(&cardGroup, cardGroupID).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to find card group for adding user", err)
logger.Logger.ErrorContext(ctx, "Failed to find cardgroup for adding user", err)
return nil, err
}
if err := s.db.Model(&cardGroup).Association("Users").Append(&user); err != nil {
logger.Logger.ErrorContext(ctx, "Failed to add user to card group", err)
logger.Logger.ErrorContext(ctx, "Failed to add user to cardgroup", err)
return nil, err
}
return convertToCardGroup(cardGroup), nil
Expand All @@ -118,15 +118,15 @@ func (s *cardGroupService) RemoveUserFromCardGroup(ctx context.Context, userID i
var user repository.User
var cardGroup repository.Cardgroup
if err := s.db.WithContext(ctx).First(&user, userID).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to find user for removing from card group", err)
logger.Logger.ErrorContext(ctx, "Failed to find user for removing from cardgroup", err)
return nil, err
}
if err := s.db.WithContext(ctx).First(&cardGroup, cardGroupID).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to find card group for removing user", err)
logger.Logger.ErrorContext(ctx, "Failed to find cardgroup for removing user", err)
return nil, err
}
if err := s.db.Model(&cardGroup).Association("Users").Delete(&user); err != nil {
logger.Logger.ErrorContext(ctx, "Failed to remove user from card group", err)
logger.Logger.ErrorContext(ctx, "Failed to remove user from cardgroup", err)
return nil, err
}
return convertToCardGroup(cardGroup), nil
Expand All @@ -135,7 +135,7 @@ func (s *cardGroupService) RemoveUserFromCardGroup(ctx context.Context, userID i
func (s *cardGroupService) GetCardGroupsByUser(ctx context.Context, userID int64) ([]*model.CardGroup, error) {
var user repository.User
if err := s.db.WithContext(ctx).Preload("CardGroups").First(&user, userID).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to get card groups by user ID", err)
logger.Logger.ErrorContext(ctx, "Failed to get cardgroups by user ID", err)
return nil, err
}
var gqlCardGroups []*model.CardGroup
Expand All @@ -149,7 +149,7 @@ func (s *cardGroupService) PaginatedCardGroupsByUser(ctx context.Context, userID
var user repository.User
var cardGroups []repository.Cardgroup

// Fetch the user and preload the card groups with pagination conditions
// Fetch the user and preload the cardgroups with pagination conditions
query := s.db.WithContext(ctx).Model(&user).Where("id = ?", userID).Preload("CardGroups", func(db *gorm.DB) *gorm.DB {
if after != nil {
db = db.Where("cardgroups.id > ?", *after)
Expand All @@ -168,8 +168,8 @@ func (s *cardGroupService) PaginatedCardGroupsByUser(ctx context.Context, userID
})

if err := query.Find(&user).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to get paginated card groups by user", err)
return nil, fmt.Errorf("error fetching paginated card groups by user: %+v", err)
logger.Logger.ErrorContext(ctx, "Failed to get paginated cardgroups by user", err)
return nil, fmt.Errorf("error fetching paginated cardgroups by user: %+v", err)
}

cardGroups = user.CardGroups
Expand Down Expand Up @@ -206,7 +206,7 @@ func (s *cardGroupService) PaginatedCardGroupsByUser(ctx context.Context, userID
func (s *cardGroupService) GetCardGroupsByIDs(ctx context.Context, ids []int64) ([]*model.CardGroup, error) {
var cardGroups []*repository.Cardgroup
if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&cardGroups).Error; err != nil {
logger.Logger.ErrorContext(ctx, "Failed to retrieve card groups by IDs", err)
logger.Logger.ErrorContext(ctx, "Failed to retrieve cardgroups by IDs", err)
return nil, err
}

Expand Down
15 changes: 13 additions & 2 deletions backend/graph/services/cardgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ func (suite *CardGroupTestSuite) TestCardGroupService() {

suite.Run("Normal_CreateCardGroup", func() {

createdGroup, err := testutils.CreateUserAndCardGroup(ctx, userService, cardGroupService, roleService)
input := model.NewCardGroup{Name: "Test Group"}
createdGroup, err := cardGroupService.CreateCardGroup(context.Background(), input)

assert.NoError(t, err)
assert.Equal(t, "Test Group", createdGroup.Name)
})
Expand Down Expand Up @@ -219,12 +221,21 @@ func (suite *CardGroupTestSuite) TestCardGroupService() {

suite.Run("Normal_RemoveUserFromCardGroup", func() {

// Create a role
newRole := model.NewRole{
Name: "Test Role",
}
createdRole, err := roleService.CreateRole(ctx, newRole)
if err != nil {
suite.T().Fatalf("Failed at CreateRole: %+v", err)
}

// Create a user
newUser := model.NewUser{
Name: "Test User",
Created: time.Now(),
Updated: time.Now(),
RoleIds: []int64{}, // Add any required roles here
RoleIds: []int64{createdRole.ID}, // Add any required roles here
}
createdUser, err := userService.CreateUser(ctx, newUser)
assert.NoError(t, err)
Expand Down
Loading

0 comments on commit d903d68

Please sign in to comment.