100 lines
2.6 KiB
Go
100 lines
2.6 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.asio.asia/TapRemly/server/internal/store"
|
|
)
|
|
|
|
func (h *Handler) createGroup(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := h.requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if !decodeJSON(w, r, maxJSONBody, &req) {
|
|
return
|
|
}
|
|
name := strings.TrimSpace(req.Name)
|
|
if !validDisplayName(name, 32) {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "请填写分组名称,最多 32 个字")
|
|
return
|
|
}
|
|
g, err := h.store.CreateGroup(r.Context(), user.ID, name)
|
|
if errors.Is(err, store.ErrConflict) {
|
|
writeError(w, http.StatusConflict, "conflict", "已经有同名分组")
|
|
return
|
|
}
|
|
if err != nil {
|
|
h.log.Error("create group", "err", err)
|
|
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
|
return
|
|
}
|
|
writeOK(w, map[string]any{"id": g.ID, "name": g.Name})
|
|
}
|
|
|
|
func (h *Handler) renameGroup(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := h.requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
id, ok := parseID(r.PathValue("id"))
|
|
if !ok {
|
|
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
|
return
|
|
}
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if !decodeJSON(w, r, maxJSONBody, &req) {
|
|
return
|
|
}
|
|
name := strings.TrimSpace(req.Name)
|
|
if !validDisplayName(name, 32) {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "请填写分组名称,最多 32 个字")
|
|
return
|
|
}
|
|
g, err := h.store.RenameGroup(r.Context(), user.ID, id, name)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
|
return
|
|
}
|
|
if errors.Is(err, store.ErrConflict) {
|
|
writeError(w, http.StatusConflict, "conflict", "已经有同名分组")
|
|
return
|
|
}
|
|
if err != nil {
|
|
h.log.Error("rename group", "err", err)
|
|
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
|
return
|
|
}
|
|
writeOK(w, map[string]any{"id": g.ID, "name": g.Name})
|
|
}
|
|
|
|
func (h *Handler) deleteGroup(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := h.requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
id, ok := parseID(r.PathValue("id"))
|
|
if !ok {
|
|
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
|
return
|
|
}
|
|
err := h.store.DeleteGroup(r.Context(), user.ID, id)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
|
return
|
|
}
|
|
if err != nil {
|
|
h.log.Error("delete group", "err", err)
|
|
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
|
return
|
|
}
|
|
writeOK(w, map[string]any{})
|
|
}
|