api/routes/crud/create.go

71 lines
2.2 KiB
Go
Raw Normal View History

2018-07-10 23:45:11 +00:00
package crud
import (
2018-07-25 14:24:46 +00:00
"code.vikunja.io/api/models"
2018-07-10 23:45:11 +00:00
"github.com/labstack/echo"
"net/http"
"reflect"
2018-07-10 23:45:11 +00:00
)
// CreateWeb is the handler to create an object
func (c *WebHandler) CreateWeb(ctx echo.Context) error {
2018-07-14 15:34:59 +00:00
// Re-initialize our model
p := reflect.ValueOf(c.CObject).Elem()
p.Set(reflect.Zero(p.Type()))
2018-07-14 15:34:59 +00:00
// Get the object & bind params to struct
if err := ParamBinder(c.CObject, ctx); err != nil {
2018-07-11 12:27:16 +00:00
return echo.NewHTTPError(http.StatusBadRequest, "No or invalid model provided.")
2018-07-10 23:45:11 +00:00
}
// Get the user to pass for later checks
currentUser, err := models.GetCurrentUser(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Could not determine the current user.")
}
2018-07-12 21:16:32 +00:00
// Check rights
if !c.CObject.CanCreate(&currentUser) {
2018-07-12 21:16:32 +00:00
return echo.NewHTTPError(http.StatusForbidden)
}
2018-07-10 23:45:11 +00:00
// Create
err = c.CObject.Create(&currentUser)
2018-07-10 23:45:11 +00:00
if err != nil {
if models.IsErrListDoesNotExist(err) {
return echo.NewHTTPError(http.StatusBadRequest, "The list does not exist.")
}
if models.IsErrListTitleCannotBeEmpty(err) {
return echo.NewHTTPError(http.StatusBadRequest, "You must provide at least a list title.")
}
2018-08-30 06:09:17 +00:00
if models.IsErrListTaskCannotBeEmpty(err) {
return echo.NewHTTPError(http.StatusBadRequest, "You must provide at least a list task text.")
}
if models.IsErrUserDoesNotExist(err) {
return echo.NewHTTPError(http.StatusBadRequest, "The user does not exist.")
}
if models.IsErrNeedToBeListWriter(err) {
return echo.NewHTTPError(http.StatusForbidden, "You need to have write access on that list.")
}
if models.IsErrNamespaceNameCannotBeEmpty(err) {
return echo.NewHTTPError(http.StatusNotFound, "The namespace name cannot be empty.")
}
2018-07-14 16:29:24 +00:00
if models.IsErrTeamNameCannotBeEmpty(err) {
return echo.NewHTTPError(http.StatusBadRequest, "The team name cannot be empty.")
}
if models.IsErrTeamAlreadyHasAccess(err) {
return echo.NewHTTPError(http.StatusBadRequest, "This team already has access.")
}
if models.IsErrUserIsMemberOfTeam(err) {
return echo.NewHTTPError(http.StatusBadRequest, "This user is already a member of that team.")
}
2018-07-10 23:45:11 +00:00
return echo.NewHTTPError(http.StatusInternalServerError)
}
return ctx.JSON(http.StatusOK, c.CObject)
}