boxes-api/item_handlers.go

243 lines
6.3 KiB
Go

// item_handlers.go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/gorilla/mux"
)
func GetItemsHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
log.Info("Received %s request to %s", r.Method, r.URL)
var items []Item
// Preload tags when getting items
if err := db.Preload("Tags").Find(&items).Error; err != nil {
log.Error("Failed to fetch items: %v", err)
http.Error(w, "Failed to fetch items", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(items)
}
func CreateItemHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
var item Item
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
log.Error("Failed to decode item creation request: %v", err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
log.Info("Creating new item: %s", item.Name)
db.Create(&item)
type createItemResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
}
response := createItemResponse{
ID: item.ID,
Name: item.Name,
}
log.DatabaseAction("create", fmt.Sprintf("Created item with ID %d", item.ID))
json.NewEncoder(w).Encode(response)
}
func UploadItemImageHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
user, ok := r.Context().Value(userKey).(string)
if !ok || user == "" {
log.Warn("Unauthorized image upload attempt")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
err := r.ParseMultipartForm(10 << 20)
if err != nil {
log.Error("Failed to parse multipart form: %v", err)
http.Error(w, "Unable to parse form", http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("image")
if err != nil {
log.Error("Error retrieving file from form: %v", err)
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
vars := mux.Vars(r)
itemID := vars["id"]
var item Item
if err := db.First(&item, itemID).Error; err != nil {
log.Warn("Attempt to upload image for non-existent item with ID: %s", itemID)
http.Error(w, "Item not found", http.StatusNotFound)
return
}
if err := os.MkdirAll(*ImageStorage, 0755); err != nil {
log.Error("Failed to create image storage directory: %v", err)
http.Error(w, "Unable to create image storage directory", http.StatusInternalServerError)
return
}
filePath := fmt.Sprintf("%s/%s", *ImageStorage, handler.Filename)
outFile, err := os.Create(filePath)
if err != nil {
log.Error("Failed to create file: %v", err)
http.Error(w, "Unable to save the file", http.StatusInternalServerError)
return
}
defer outFile.Close()
_, err = io.Copy(outFile, file)
if err != nil {
log.Error("Failed to save file: %v", err)
http.Error(w, "Unable to save the file", http.StatusInternalServerError)
return
}
item.ImagePath = filePath
if err := db.Save(&item).Error; err != nil {
log.Error("Failed to update item with image path: %v", err)
http.Error(w, "Unable to save image path in database", http.StatusInternalServerError)
return
}
log.Info("Image uploaded successfully for item %s by user %s", itemID, user)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"imagePath": filePath})
}
func GetItemImageHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
vars := mux.Vars(r)
itemID := vars["id"]
var item Item
if err := db.First(&item, itemID).Error; err != nil {
log.Info("Item not found, using default image for ID: %s", itemID)
item.ImagePath = "images/default.jpg"
} else if item.ImagePath == "" {
item.ImagePath = "images/default.jpg"
}
imageFile, err := os.Open(item.ImagePath)
if err != nil {
log.Error("Error opening image file: %v", err)
item.ImagePath = "images/default.jpg"
return
}
defer imageFile.Close()
imageData, err := io.ReadAll(imageFile)
if err != nil {
log.Error("Error reading image file: %v", err)
item.ImagePath = "images/default.jpg"
return
}
contentType := http.DetectContentType(imageData)
w.Header().Set("Content-Type", contentType)
w.Write(imageData)
}
func SearchItemsHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
query := r.URL.Query().Get("q")
if query == "" {
log.Warn("Search attempt with empty query")
http.Error(w, "Search query is required", http.StatusBadRequest)
return
}
log.Info("Searching for items with query: %s", query)
var items []Item
db.Where("name GLOB ? OR description GLOB ?", "*"+query+"*", "*"+query+"*").Find(&items)
json.NewEncoder(w).Encode(items)
}
func GetItemHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.Preload("Tags").First(&item, id).Error; err != nil {
log.Warn("Item not found with ID: %s", id)
http.Error(w, "Item not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(item)
}
func GetItemsInBoxHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
vars := mux.Vars(r)
id := vars["id"]
var items []Item
if err := db.Preload("Tags").Where("box_id = ?", id).Find(&items).Error; err != nil {
log.Warn("Failed to fetch items for box ID: %s", id)
http.Error(w, "Items not found", http.StatusNotFound)
return
}
log.Info("Retrieved %d items from box %s", len(items), id)
json.NewEncoder(w).Encode(items)
}
func UpdateItemHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.First(&item, id).Error; err != nil {
log.Warn("Attempt to update non-existent item with ID: %s", id)
http.Error(w, "Item not found", http.StatusNotFound)
return
}
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
log.Error("Failed to decode item update request: %v", err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
log.DatabaseAction("update", fmt.Sprintf("Updated item with ID %s", id))
db.Save(&item)
json.NewEncoder(w).Encode(item)
}
func DeleteItemHandler(w http.ResponseWriter, r *http.Request) {
log := GetLogger()
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.First(&item, id).Error; err != nil {
log.Warn("Attempt to delete non-existent item with ID: %s", id)
http.Error(w, "Item not found", http.StatusNotFound)
return
}
log.DatabaseAction("delete", fmt.Sprintf("Deleted item with ID %s", id))
db.Delete(&item)
w.WriteHeader(http.StatusNoContent)
}