routes created, users controllers, user_repository, model users.go, main.go

This commit is contained in:
Vicode92 2024-03-20 12:37:59 +00:00
commit 9f539f847c
8 changed files with 213 additions and 0 deletions

34
cmd/main.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"gorm.io/gorm"
"github.com/gin-gonic/gin"
"plateMate/controllers"
"plateMate/repositories"
"plateMate/models"
)
func main() {
// Inicializar la conexión de base de datos (db)
db, err := gorm.Open("tu_driver_de_base_de_datos", "tu_dsn_de_conexion")
if err != nil {
panic("Error al conectar a la base de datos: " + err.Error())
}
defer db.Close()
// Auto migración de modelos
db.AutoMigrate(&models.User{}, &models.Plate{}, &models.Order{})
// Crear una instancia del repositorio de usuarios y pasar la conexión de base de datos
userRepository := repositories.NewUserRepository(db)
// Crear una instancia de Gin
router := gin.Default()
// Configurar las rutas y pasar el repositorio de usuarios a los controladores
controllers.ConfigureUserRoutes(router, userRepository)
// Aquí puedes configurar las rutas para otros recursos (platos, pedidos, etc.)
// Iniciar la aplicación Gin
router.Run(":8080")
}

34
config/routes.go Normal file
View File

@ -0,0 +1,34 @@
package config
import (
"github.com/gin-gonic/gin"
"plateMate/controllers"
)
func ConfigureRoutes(router *gin.Engine) {
// users endpoints
router.GET("/users", controllers.GetUsers)
router.GET("/users/:id", controllers.GetUserById)
router.POST("/users", controllers.CreateUser)
router.PUT("/users/:id", controllers.UpdateUser)
router.DELETE("/users/:id", controllers.DeleteUser)
// plates endpoints
router.GET("/plates", controllers.GetPlates)
router.GET("/plates/:id", controllers.GetPlateById)
router.POST("/plates", controllers.CreatePlate)
router.PUT("/plates/:id", controllers.UpdatePlate)
router.DELETE("/plates/:id", controllers.DeletePlate)
// orders endpoints
router.GET("/orders", controllers.GetOrders)
router.GET("/orders/:id", controllers.GetOrderById)
router.POST("/orders", controllers.CreateOrder)
router.PUT("/orders/:id", controllers.UpdateOrder)
router.DELETE("/orders/:id", controllers.DeleteOrder)
// auth endpoints
router.POST("/login", controllers.Login)
router.POST("/logout", controllers.Logout)
router.POST("/register", controllers.Register)
}

0
controllers/auth.go Normal file
View File

0
controllers/orders.go Normal file
View File

0
controllers/plates.go Normal file
View File

81
controllers/users.go Normal file
View File

@ -0,0 +1,81 @@
package controllers
import (
"net/http"
"github.com/gin-gonic/gin"
"plateMate/models"
)
// Create a new user
func CreateUser(c *gin.Context) {
var newUser models.User
if err := c.ShouldBindJSON(&newUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Call the repository function to create a new user
if err := repositories.CreateUser(&newUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error creating user"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "User created", "user": newUser})
}
// Get all users
func GetUsers(c *gin.Context) {
users, err := repositories.GetAllUsers()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting users"})
return
}
c.JSON(http.StatusOK, users)
}
// Get a user by ID
func GetUserById(c *gin.Context) {
userID := c.Param("id")
user, err := repositories.GetUserById(userID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
c.JSON(http.StatusOK, user)
}
// Update a user
func UpdateUser(c *gin.Context) {
userID := c.Param("id")
var updatedUser models.User
if err := c.ShouldBindJSON(&updatedUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Call the repository function to update a user
if err := repositories.UpdateUser(userID, &updatedUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error updating user"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "User updated successfully"})
}
// Delete a user
func DeleteUser(c *gin.Context) {
userID := c.Param("id")
if err := repositories.DeleteUser(userID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error deleting user"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "User deleted successfully"})
}

View File

@ -0,0 +1,49 @@
package repositories
import (
"gorm.io/gorm"
"plateMate/models"
)
// UserRepository representa un repositorio para manejar operaciones relacionadas con usuarios en la base de datos
type UserRepository struct {
db *gorm.DB
}
// NewUserRepository crea una nueva instancia de UserRepository
func NewUserRepository(db *gorm.DB) *UserRepository {
return &UserRepository{db}
}
// Create crea un nuevo usuario en la base de datos
func (ur *UserRepository) Create(user *models.User) error {
return ur.db.Create(user).Error
}
// GetAll devuelve todos los usuarios de la base de datos
func (ur *UserRepository) GetAll() ([]models.User, error) {
var users []models.User
if err := ur.db.Find(&users).Error; err != nil {
return nil, err
}
return users, nil
}
// GetByID devuelve un usuario por su ID de la base de datos
func (ur *UserRepository) GetByID(userID uint) (*models.User, error) {
var user models.User
if err := ur.db.First(&user, userID).Error; err != nil {
return nil, err
}
return &user, nil
}
// Update actualiza la información de un usuario en la base de datos
func (ur *UserRepository) Update(user *models.User) error {
return ur.db.Save(user).Error
}
// Delete elimina un usuario de la base de datos
func (ur *UserRepository) Delete(user *models.User) error {
return ur.db.Delete(user).Error
}

15
models/users.go Normal file
View File

@ -0,0 +1,15 @@
package models
import (
"time"
)
type User struct {
ID uint `gorm:"primary_key"`
Name string
LastName string
Email string
Password string `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}