A FAIRE.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

102 lines
2.2 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### api ####### Copyright (c) 2021 mls-361 ##################################################### MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package api
import (
"net/http"
"forge.chapril.org/armen/jw"
"forge.chapril.org/armen/model"
"forge.chapril.org/mls-361/errors"
"forge.chapril.org/mls-361/jsonapi"
"forge.chapril.org/mls-361/uuid"
"forge.chapril.org/armen/armen/internal/components"
"forge.chapril.org/armen/armen/internal/middleware"
)
const (
_maxBodySize = 1024 * 32
)
type api struct {
logger components.Logger
model components.Model
}
func newAPI(ccs *components.Components) *api {
return &api{
logger: ccs.Logger.NewLogger(uuid.New(), "api"),
model: ccs.Model,
}
}
func (api *api) middleware(hf jsonapi.HandlerFunc) jsonapi.Handler {
return middleware.Trace(hf, api.logger)
}
func (api *api) createJob(r *jsonapi.Request) {
job := new(jw.Job)
if r.Decode(_maxBodySize, job) != nil {
return
}
job, err := api.model.CreateJob(job)
if err != nil {
if errors.Is(err, model.ErrValidation) {
r.BadRequest(err)
} else {
r.InternalServerError(err)
}
return
}
if job == nil {
r.RenderNoContent()
return
}
r.RenderJSON(http.StatusCreated, job, api.logger)
}
func (api *api) nextJob(r *jsonapi.Request) {
namespace := r.Param("namespace")
if namespace == "" {
r.BadRequest(errors.New("namespace must not be empty")) ////////////////////////////////////////////////////////
}
job, err := api.model.NextJob(namespace)
if err != nil {
r.InternalServerError(err)
return
}
if job == nil {
r.RenderNoContent()
return
}
r.RenderJSON(http.StatusOK, job, api.logger)
}
func Build(ccs *components.Components) {
api := newAPI(ccs)
router := ccs.Router
router.Get("/status", api.middleware(func(r *jsonapi.Request) {
r.RenderOK()
}))
router.Post("/job/create", api.middleware(api.createJob))
router.Get("/job/next/:namespace", api.middleware(api.nextJob))
}
/*
######################################################################################################## @(°_°)@ #######
*/