Files
pokeval/api/card_handler.go
2025-04-28 00:04:14 +02:00

91 lines
2.1 KiB
Go

package api
import (
"encoding/json"
"net/http"
"pokeval/db"
"pokeval/models"
"strconv"
"github.com/gorilla/mux"
)
// GET /api/v1/cards/{id}
func GetCard(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cardID, _ := strconv.Atoi(vars["id"])
var card models.Card
err := db.DB.QueryRow("SELECT cards_id, cards_number, cards_name FROM cards WHERE cards_id = ?", cardID).
Scan(&card.ID, &card.Number, &card.Name)
if err != nil {
http.Error(w, "{}", 404)
return
}
// Attribute laden
rows, _ := db.DB.Query(`
SELECT ak.attributekeys_name, a.attributes_value
FROM attributes a
JOIN attributekeys ak ON ak.attributekeys_id = a.attributes_key
WHERE a.attributes_card = ?`, cardID)
attrs := make(map[string]interface{})
for rows.Next() {
var key string
var value []byte
rows.Scan(&key, &value)
var parsed interface{}
json.Unmarshal(value, &parsed)
attrs[key] = parsed
}
card.Attributes = attrs
json.NewEncoder(w).Encode(card)
}
// GET /api/v1/cards/{id}
/*func GetCard(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, _ := strconv.Atoi(vars["id"])
row := db.DB.QueryRow("SELECT id, name, number FROM cards WHERE id = ?", id)
var cardID int
var name, number string
err := row.Scan(&cardID, &name, &number)
if err != nil {
http.Error(w, "Karte nicht gefunden", http.StatusNotFound)
return
}
resp := map[string]interface{}{
"id": cardID,
"name": name,
"number": number,
}
json.NewEncoder(w).Encode(resp)
}*/
// POST /api/v1/cards
func CreateCard(w http.ResponseWriter, r *http.Request) {
var input struct {
Name string `json:"name"`
Number string `json:"number"`
SeriesID int `json:"series_id"`
}
json.NewDecoder(r.Body).Decode(&input)
_, err := db.DB.Exec("INSERT INTO cards (name, number, series_id) VALUES (?, ?, ?)",
input.Name, input.Number, input.SeriesID)
if err != nil {
http.Error(w, "Fehler beim Erstellen der Karte", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"message": "Karte erfolgreich erstellt"})
}