busybar / internal / services / user.service.go
user.service.go
Raw
package services

import (
	"context"
	"errors"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/danielrhuynh/busybar/internal/models"
	"github.com/danielrhuynh/busybar/pkg/database"
)

func UpdateUser(userId int, req models.RegistrationRequest) (*string, error) {
	sql, args, err := database.PSQL.Update("users").
		Where(squirrel.Eq{"id": userId}).
		Set("first_name", req.FirstName).
		Set("last_name", req.LastName).
		Set("degree_program", req.Program).
		Set("school", req.School).
		Set("gender", req.Gender).
		Set("email", req.Email).
		Set("degree_term", req.Term).
		Set("sexual_orientation", req.SexualOrientation).
		Suffix("RETURNING id").
		ToSql()

	if err != nil {
		fmt.Println("Error constructing SQL for user insertion:", err)
		return nil, err
	}

	var userID string
	err = database.DB.QueryRow(context.Background(), sql, args...).Scan(&userID)
	if err != nil {
		fmt.Println("Error inserting user into database:", err)
		return nil, err
	}

	return &userID, nil
}

func DeleteAccount(userId int) error {
	var exists int
	checkSql, checkArgs, err := database.PSQL.Select("1").
		From("users").
		Where(squirrel.Eq{"id": userId}).
		ToSql()

	if err != nil {
		return err
	}

	err = database.DB.QueryRow(context.Background(), checkSql, checkArgs...).Scan(&exists)
	if err != nil {
		if err.Error() == "no rows in result set" {
			return errors.New("account does not exist")
		}
		return err
	}

	deleteSql, deleteArgs, err := database.PSQL.Delete("users").
		Where(squirrel.Eq{"id": userId}).
		ToSql()

	if err != nil {
		return err
	}

	_, err = database.DB.Exec(context.Background(), deleteSql, deleteArgs...)
	if err != nil {
		return err
	}

	return nil
}