Files
status/router/controller/service/controller.go

108 lines
2.5 KiB
Go

package service
import (
"net/http"
"git.ostiwe.com/ostiwe-com/status/modules/jwt"
"git.ostiwe.com/ostiwe-com/status/modules/log"
http2 "git.ostiwe.com/ostiwe-com/status/pkg/http"
"git.ostiwe.com/ostiwe-com/status/repository"
"git.ostiwe.com/ostiwe-com/status/router/controller"
"git.ostiwe.com/ostiwe-com/status/router/midlleware"
"git.ostiwe.com/ostiwe-com/status/transform"
"github.com/go-andiamo/chioas"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
type Controller struct {
serviceRepository repository.Service
}
func (c *Controller) New() controller.Controller {
return &Controller{
serviceRepository: repository.NewServiceRepository(),
}
}
func (c *Controller) Group(r chi.Router) {
c.public(r)
c.internal(r)
}
func (c *Controller) public(r chi.Router) {
r.Get("/api/public/service", c.GetAllServicesPublic)
}
func (c *Controller) internal(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(
jwtauth.Verifier(jwt.TokenAuth),
jwtauth.Authenticator(jwt.TokenAuth),
midlleware.SetUserFromJWT,
)
r.Get("/api/v1/service", c.GetAllServices)
})
}
func (c *Controller) GetAllServicesPublic(w http.ResponseWriter, r *http.Request) {
items, err := c.serviceRepository.All(r.Context(), -1, 0, true)
if err != nil {
log.Global.Get(log.SERVER).Error(err)
writeErr := http2.NewResponseErrBuilder().
WithMessage("Fetch service error").
WithStatusCode(http.StatusInternalServerError).
Send(w, r)
if writeErr != nil {
log.Global.Get(log.SERVER).Error(writeErr)
}
return
}
err = http2.JSON(w, transform.PublicServices(items...), http.StatusOK)
if err != nil {
log.Global.Get(log.SERVER).Error(err)
}
}
func (c *Controller) GetAllServices(w http.ResponseWriter, r *http.Request) {
limit, offset, errReady := http2.ExtractLimitOffset(r)
if errReady != nil {
err := errReady.Send(w)
if err != nil {
log.Global.Get(log.SERVER).Error(err)
return
}
return
}
items, err := c.serviceRepository.All(r.Context(), limit, offset, false)
if err != nil {
log.Global.Get(log.SERVER).Error(err)
writeErr := http2.NewResponseErrBuilder().
WithMessage("Fetch service error").
WithStatusCode(http.StatusInternalServerError).
Send(w, r)
if writeErr != nil {
log.Global.Get(log.SERVER).Error(writeErr)
}
return
}
err = http2.JSON(w, items, http.StatusOK)
if err != nil {
log.Global.Get(log.SERVER).Error(err)
}
}
func (c *Controller) Documentate() (*chioas.Paths, *chioas.Components) {
return nil, nil
}