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.
72 lines
1.9 KiB
72 lines
1.9 KiB
package api
|
|
|
|
import (
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/auth"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/database"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/models"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/slerrors"
|
|
"github.com/gin-gonic/gin"
|
|
"time"
|
|
)
|
|
|
|
func Items(g *gin.RouterGroup, db database.Database) {
|
|
g.Use(scopeIDMiddleware(db))
|
|
|
|
g.GET("/:id", handler("item", func(c *gin.Context) (interface{}, error) {
|
|
id, err := reqInt(c, "id")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
item, err := db.Items(getScope(c).ID).Find(c.Request.Context(), id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, member := range getScope(c).Members {
|
|
if member.ID == item.OwnerID {
|
|
item.Owner = &member
|
|
}
|
|
}
|
|
|
|
return item, nil
|
|
}))
|
|
|
|
g.POST("/", handler("item", func(c *gin.Context) (interface{}, error) {
|
|
item := &models.Item{}
|
|
err := c.BindJSON(item)
|
|
if err != nil {
|
|
return nil, slerrors.BadRequest("Invalid JSON input: " + err.Error())
|
|
}
|
|
|
|
item.CreatedTime = time.Now()
|
|
|
|
if item.Name == "" {
|
|
return nil, slerrors.BadRequest("Blank item name not allowed")
|
|
}
|
|
if item.OwnerID == "" {
|
|
item.OwnerID = auth.UserID(c)
|
|
} else if getScope(c).HasMember(item.OwnerID) {
|
|
return nil, slerrors.Forbidden("Owner is not part of scope.")
|
|
}
|
|
if item.ProjectRequirementID != nil {
|
|
// TODO: Ensure project requirement exists in scope.
|
|
return nil, slerrors.Forbidden("TODO: check project requirement ID.")
|
|
}
|
|
for _, stat := range item.Stats {
|
|
if getScope(c).Stat(stat.ID) == nil {
|
|
return nil, slerrors.Forbidden("One or more stats are not part of scope.")
|
|
}
|
|
if stat.Acquired == 0 && stat.Required == 0 {
|
|
return nil, slerrors.BadRequest("0/0 stats are not allowed when creating items.")
|
|
}
|
|
}
|
|
|
|
item, err = db.Items(getScope(c).ID).Create(c.Request.Context(), *item)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
item.Owner = getScope(c).Member(item.OwnerID)
|
|
|
|
return item, err
|
|
}))
|
|
}
|