DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

29412f92fc0b7b543cbba8a00f1f599333a3ab3b — Jonni Liljamo 1 year, 8 months ago 7cea5a1
feat(sdbapi): endpoint for getting own games
4 files changed, 68 insertions(+), 1 deletions(-)

M sdbapi/apierror/apierror.go
A sdbapi/db/game.go
A sdbapi/handlers/mygames.go
M sdbapi/main.go
M sdbapi/apierror/apierror.go => sdbapi/apierror/apierror.go +1 -0
@@ 24,4 24,5 @@ const (
	GameCreationFailed string = "game creation failed"
	GetAllFormingFailed string = "something went wrong while fetching all forming games"
	GameStatePatchFailed string = "failed to patch game state"
	NoGamesForUser = "no games found for user"
)

A sdbapi/db/game.go => sdbapi/db/game.go +28 -0
@@ 0,0 1,28 @@
/*
 * This file is part of sdbapi
 * Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

package db

import (
	"api/apierror"
	"api/models"

	"errors"
)

// get games for a specific user with email
func GetGamesForUser(id string) ([]models.Game, error) {
	var games []models.Game
	game_records := DbConn.Where("p1 = ? OR p2 = ?", id, id).Find(&games)
	if game_records.Error != nil {
		return []models.Game{}, errors.New(apierror.NoGamesForUser)
	}

	return games, nil
}


A sdbapi/handlers/mygames.go => sdbapi/handlers/mygames.go +38 -0
@@ 0,0 1,38 @@
/*
 * This file is part of sdbapi
 * Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

package handlers

import (
	"api/apierror"
	"api/db"
	"api/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

func MyGames(c *gin.Context) {
	var user models.User
	record := db.DbConn.Where("email = ?", c.GetString("email")).First(&user)
	if record.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": apierror.UserNotFound})
		c.Abort()
		return
	}

	games, err := db.GetGamesForUser(user.ID)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		c.Abort()
		return
	}

	c.JSON(http.StatusOK, gin.H{"games": games})
}


M sdbapi/main.go => sdbapi/main.go +1 -1
@@ 51,7 51,7 @@ func createRouter() *gin.Engine {
			game.GET("/all_forming", handlers.FormingGames)
			game.POST("/create", handlers.CreateGame)
			game.PATCH("/:id/state", handlers.PatchGameState)
			//game.GET("/for_user/:id", handlers.UsersGames)
			game.GET("/my_games", handlers.MyGames)
		}
	}
	return router