Add Preloading and sending NameWithParent field with default value being inp.Name

This commit is contained in:
qowevisa 2024-11-27 21:59:47 +02:00
parent 87c5676846
commit 8807235dad

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
} }