Add POST /user/{userId}/goals (#26)

Closes #4

Reviewed-on: #26
This commit was merged in pull request #26.
This commit is contained in:
2025-05-08 14:02:58 +02:00
parent aa26a8f338
commit d251d41650
4 changed files with 190 additions and 3 deletions

View File

@@ -2,8 +2,9 @@ package main
import (
"errors"
"gitea.seeseepuff.be/seeseemelk/mysqlite"
"log"
"gitea.seeseepuff.be/seeseemelk/mysqlite"
)
type Db struct {
@@ -86,3 +87,44 @@ func (db *Db) GetUserGoals(userId int) ([]Goal, error) {
}
return goals, nil
}
func (db *Db) CreateGoal(userId int, goal *CreateGoalRequest) (int, error) {
// Check if user exists before attempting to create a goal
exists, err := db.UserExists(userId)
if err != nil {
return 0, err
}
if !exists {
return 0, errors.New("user does not exist")
}
tx, err := db.db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
// Insert the new goal
err = tx.Query("insert into goals (user_id, name, target, progress, weight) values (?, ?, ?, 0, ?)").
Bind(userId, goal.Name, goal.Target, goal.Weight).
Exec()
if err != nil {
return 0, err
}
// Get the last inserted ID
var lastId int
err = tx.Query("select last_insert_rowid()").ScanSingle(&lastId)
if err != nil {
return 0, err
}
// Commit the transaction
err = tx.Commit()
if err != nil {
return 0, err
}
return lastId, nil
}