Potion/internal/app/service/user_service.go
Hayden Hargreaves 55c6a99bb1 (FEAT/DOC): Wired the backend to the UI for the recipe page!
The route will now display real, live data from the DB! Errors are not
handled very well, just returned as JSON for now. Need to implement an
error page for states when errors occur.

This commit also includes lots of documentation for the various
service/repository methods. I am trying to not let docs fall through the
cracks, but I am not perfect lol.
2025-07-02 22:53:15 -07:00

56 lines
1.8 KiB
Go

package service
import (
"fmt"
"github.com/gin-gonic/gin"
domain "github.com/haydenhargreaves/Potion/internal/domain/user"
)
// UserService implements the domain.UserService defined in the domain module.
type UserService struct {
userRepository domain.UserRepository
}
// Compile-time check to ensure the UserService implements domain.UserService
var _ domain.UserService = (*UserService)(nil)
// NewUserService creates a user service object which can be passed into the context. The service
// requires a user repository which it will use to hit the database when needed.
func NewUserService(userRepository domain.UserRepository) domain.UserService {
return &UserService{userRepository: userRepository}
}
// GetAuthenicatedUser will return the user the is currently authenticated. This assumes that the
// user is actually logged in, if not, a blank user will be returned. To ensure success, call the
// `domain.IsLoggedIn()` function first to ensure the user is logged in. If that passes, this
// function should yield a result.
func (s *UserService) GetAuthenicatedUser(ctx *gin.Context) domain.User {
val, ok := ctx.Get("userId")
if !ok {
return domain.User{}
}
id := val.(int)
user, err := s.userRepository.GetUser(id)
if err != nil {
return domain.User{}
}
return *user
}
// GetUser will get a user from the database via its ID. This is not related to the Google ID in
// any capacity. Any errors will be bubbled to the caller. Furthermore, if the user is nil, an error
// will be returned, so the caller does not need to check for a nil user (e.g., if the error is nil
// the user exists)
func (s *UserService) GetUser(id int) (*domain.User, error) {
user, err := s.userRepository.GetUser(id)
if user == nil {
return nil, fmt.Errorf("Failed to get user from database. Nil result.")
}
return user, err
}