62 lines
1.8 KiB
Go
62 lines
1.8 KiB
Go
package query
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/auth"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/rbac"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type HTTP struct {
|
|
Service Service
|
|
Auth auth.HTTP
|
|
}
|
|
|
|
func (h HTTP) Register(mux *http.ServeMux) {
|
|
mux.Handle("GET /api/v1/alerts", h.Auth.Require(rbac.AlertsRead, http.HandlerFunc(h.list)))
|
|
mux.Handle("GET /api/v1/alerts/{id}", h.Auth.Require(rbac.AlertsRead, http.HandlerFunc(h.get)))
|
|
mux.Handle("GET /api/v1/events/{id}/alerts", h.Auth.Require(rbac.EventsRead, http.HandlerFunc(h.forEvent)))
|
|
}
|
|
func (h HTTP) list(w http.ResponseWriter, r *http.Request) {
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
items, err := h.Service.List(r.Context(), limit, r.URL.Query().Get("before"))
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": "读取预警失败"})
|
|
return
|
|
}
|
|
next := ""
|
|
if len(items) > 0 {
|
|
next = items[len(items)-1].ID
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": items, "next": next})
|
|
}
|
|
func (h HTTP) get(w http.ResponseWriter, r *http.Request) {
|
|
item, err := h.Service.Get(r.Context(), r.PathValue("id"))
|
|
if err != nil {
|
|
status := 500
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
status = 404
|
|
}
|
|
writeJSON(w, status, map[string]string{"error": "预警不存在"})
|
|
return
|
|
}
|
|
writeJSON(w, 200, item)
|
|
}
|
|
func (h HTTP) forEvent(w http.ResponseWriter, r *http.Request) {
|
|
items, err := h.Service.ForEvent(r.Context(), r.PathValue("id"))
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": "读取关联预警失败"})
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": items})
|
|
}
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|