|
|
@@ -0,0 +1,52 @@
|
|
|
+package routes
|
|
|
+
|
|
|
+import (
|
|
|
+ "encoding/json"
|
|
|
+ "net/http"
|
|
|
+
|
|
|
+ "github.com/CesarSSH/api-estudiantes/db"
|
|
|
+ "github.com/CesarSSH/api-estudiantes/models"
|
|
|
+ "gorm.io/gorm"
|
|
|
+)
|
|
|
+
|
|
|
+func GetEstudiantesHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
+ var estudiantes []models.Estudiante
|
|
|
+ db.DB.Find(&estudiantes)
|
|
|
+ json.NewEncoder(w).Encode(&estudiantes)
|
|
|
+}
|
|
|
+
|
|
|
+func PostEstudianteHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
+ var estudiante models.Estudiante
|
|
|
+ err := json.NewDecoder(r.Body).Decode(&estudiante)
|
|
|
+ if err != nil {
|
|
|
+ w.WriteHeader(http.StatusBadRequest) // Error 400
|
|
|
+ w.Write([]byte("Error decoding JSON: " + err.Error()))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ // Verifica si la CategoriaID existe
|
|
|
+ var categoria models.Categoria
|
|
|
+ result := db.DB.First(&categoria, estudiante.CategoriaID) // Busca la categoria por ID
|
|
|
+ if result.Error != nil {
|
|
|
+ if result.Error == gorm.ErrRecordNotFound {
|
|
|
+ w.WriteHeader(http.StatusNotFound) // Error 404
|
|
|
+ w.Write([]byte("El ID de esa categoria no existe"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ // Si hay un error diferente, maneja el error
|
|
|
+ w.WriteHeader(http.StatusInternalServerError) // Error 500
|
|
|
+ w.Write([]byte("Error en la query de la DB: " + result.Error.Error()))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ // Si el AttributeID existe, crea el nuevo estudiante
|
|
|
+ estudianteCreado := db.DB.Create(&estudiante)
|
|
|
+ if estudianteCreado.Error != nil {
|
|
|
+ w.WriteHeader(http.StatusBadRequest) // Error 400
|
|
|
+ w.Write([]byte("Error al crear el estudiante: " + estudianteCreado.Error.Error()))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ w.WriteHeader(http.StatusCreated) // Código 201
|
|
|
+ json.NewEncoder(w).Encode(&estudiante) // Devuelve el estudiante creado
|
|
|
+}
|