82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
|
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"})
|
||
|
}
|
||
|
|
||
|
|