Compare commits

...

3 Commits

3 changed files with 20 additions and 7 deletions

View File

@ -39,9 +39,6 @@ var (
) )
func (c *Category) BeforeSave(tx *gorm.DB) error { func (c *Category) BeforeSave(tx *gorm.DB) error {
if c.ParentID == c.ID {
return ERROR_CATEGORY_SELF_REFERENCING
}
if c.ParentID != 0 { if c.ParentID != 0 {
var parent Category var parent Category
if err := tx.Find(&parent, c.ParentID).Error; err != nil { if err := tx.Find(&parent, c.ParentID).Error; err != nil {
@ -63,3 +60,10 @@ func (c *Category) BeforeSave(tx *gorm.DB) error {
} }
return nil return nil
} }
func (c *Category) AfterCreate(tx *gorm.DB) error {
if c.ParentID == c.ID {
return ERROR_CATEGORY_SELF_REFERENCING
}
return nil
}

View File

@ -1,16 +1,23 @@
package handlers package handlers
import ( import (
"fmt"
"git.qowevisa.me/Qowevisa/fin-check-api/db" "git.qowevisa.me/Qowevisa/fin-check-api/db"
"git.qowevisa.me/Qowevisa/fin-check-api/types" "git.qowevisa.me/Qowevisa/fin-check-api/types"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
var categoryTransform func(*db.Category) types.DbCategory = func(inp *db.Category) types.DbCategory { var categoryTransform func(*db.Category) types.DbCategory = func(inp *db.Category) types.DbCategory {
nameWithParent := inp.Name
if inp.Parent != nil {
nameWithParent = fmt.Sprintf("%s -> %s", inp.Parent.Name, inp.Name)
}
return types.DbCategory{ return types.DbCategory{
ID: inp.ID, ID: inp.ID,
Name: inp.Name, Name: inp.Name,
ParentID: inp.ParentID, ParentID: inp.ParentID,
NameWithParent: nameWithParent,
} }
} }
@ -50,7 +57,7 @@ func CategoryGetAll(c *gin.Context) {
} }
dbc := db.Connect() dbc := db.Connect()
var entities []*db.Category var entities []*db.Category
if err := dbc.Find(&entities, db.Category{UserID: userID}).Error; err != nil { if err := dbc.Preload("Parent").Find(&entities, db.Category{UserID: userID}).Error; err != nil {
c.JSON(500, types.ErrorResponse{Message: err.Error()}) c.JSON(500, types.ErrorResponse{Message: err.Error()})
return return
} }

View File

@ -42,6 +42,8 @@ type DbCategory struct {
// Parent is used as a infinite sub-category structure // Parent is used as a infinite sub-category structure
// Can be 0 // Can be 0
ParentID uint `json:"parent_id" example:"0"` ParentID uint `json:"parent_id" example:"0"`
// Purely UI things
NameWithParent string `json:"name_with_parent" example:"World -> Moldova"`
} }
type DbDebt struct { type DbDebt struct {