Add POST /user/{userId}/goals (#26)
Closes #4 Reviewed-on: #26
This commit was merged in pull request #26.
This commit is contained in:
@@ -4,11 +4,12 @@ import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
@@ -92,6 +93,46 @@ func getUserGoals(c *gin.Context) {
|
||||
c.IndentedJSON(http.StatusOK, goals)
|
||||
}
|
||||
|
||||
func createUserGoal(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid user ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var goalRequest CreateGoalRequest
|
||||
if err := c.ShouldBindJSON(&goalRequest); err != nil {
|
||||
log.Printf("Error parsing request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate request
|
||||
if goalRequest.Name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Goal name cannot be empty"})
|
||||
return
|
||||
}
|
||||
|
||||
// Create goal in database
|
||||
goalId, err := db.CreateGoal(userId, &goalRequest)
|
||||
if err != nil {
|
||||
log.Printf("Error creating goal: %v", err)
|
||||
if err.Error() == "user does not exist" {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Could not create goal"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Return created goal ID
|
||||
response := CreateGoalResponse{ID: goalId}
|
||||
c.IndentedJSON(http.StatusCreated, response)
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
Initialises the database, and then starts the server.
|
||||
@@ -105,6 +146,7 @@ func start(ctx context.Context, config *ServerConfig) {
|
||||
router.GET("/api/users", getUsers)
|
||||
router.GET("/api/user/:userId", getUser)
|
||||
router.GET("/api/user/:userId/goals", getUserGoals)
|
||||
router.POST("/api/user/:userId/goals", createUserGoal)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + config.Port,
|
||||
|
||||
Reference in New Issue
Block a user