autobrr/internal/http/action.go
Ludvig Lundgren 4d40d41628
Refactor irc client (#19)
* refactor: update http handlers

* feat: add trace log level

* refactir: irc handler

* refactor(definitions): add irc settings and invite cmd:

* feat: add dft values to inputs

* refactor: indexer irc forms

* refactor(definitions): fix nickserv.password var:

* feat: pre fill indexer name field

* refactor: handle stopping and updates
2021-08-29 23:23:02 +02:00

113 lines
2.6 KiB
Go

package http
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/autobrr/autobrr/internal/domain"
"github.com/go-chi/chi"
)
type actionService interface {
Fetch() ([]domain.Action, error)
Store(action domain.Action) (*domain.Action, error)
Delete(actionID int) error
ToggleEnabled(actionID int) error
}
type actionHandler struct {
encoder encoder
service actionService
}
func newActionHandler(encoder encoder, service actionService) *actionHandler {
return &actionHandler{
encoder: encoder,
service: service,
}
}
func (h actionHandler) Routes(r chi.Router) {
r.Get("/", h.getActions)
r.Post("/", h.storeAction)
r.Delete("/{id}", h.deleteAction)
r.Put("/{id}", h.updateAction)
r.Patch("/{id}/toggleEnabled", h.toggleActionEnabled)
}
func (h actionHandler) getActions(w http.ResponseWriter, r *http.Request) {
actions, err := h.service.Fetch()
if err != nil {
// encode error
}
h.encoder.StatusResponse(r.Context(), w, actions, http.StatusOK)
}
func (h actionHandler) storeAction(w http.ResponseWriter, r *http.Request) {
var data domain.Action
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// encode error
return
}
action, err := h.service.Store(data)
if err != nil {
// encode error
}
h.encoder.StatusResponse(r.Context(), w, action, http.StatusCreated)
}
func (h actionHandler) updateAction(w http.ResponseWriter, r *http.Request) {
var data domain.Action
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// encode error
return
}
action, err := h.service.Store(data)
if err != nil {
// encode error
}
h.encoder.StatusResponse(r.Context(), w, action, http.StatusCreated)
}
func (h actionHandler) deleteAction(w http.ResponseWriter, r *http.Request) {
actionID, err := parseInt(chi.URLParam(r, "id"))
if err != nil {
h.encoder.StatusResponse(r.Context(), w, errors.New("bad param id"), http.StatusBadRequest)
}
if err := h.service.Delete(actionID); err != nil {
// encode error
}
h.encoder.StatusResponse(r.Context(), w, nil, http.StatusNoContent)
}
func (h actionHandler) toggleActionEnabled(w http.ResponseWriter, r *http.Request) {
actionID, err := parseInt(chi.URLParam(r, "id"))
if err != nil {
h.encoder.StatusResponse(r.Context(), w, errors.New("bad param id"), http.StatusBadRequest)
}
if err := h.service.ToggleEnabled(actionID); err != nil {
// encode error
}
h.encoder.StatusResponse(r.Context(), w, nil, http.StatusCreated)
}
func parseInt(s string) (int, error) {
u, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
return int(u), nil
}