From 12fd07c0a3f5427453b15c31b4044918fe435cad Mon Sep 17 00:00:00 2001 From: qowevisa Date: Sat, 3 Aug 2024 10:49:46 +0300 Subject: [PATCH] Add Category.BeforeSave func --- db/category.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/db/category.go b/db/category.go index b02d183..87a341f 100644 --- a/db/category.go +++ b/db/category.go @@ -1,6 +1,10 @@ package db -import "gorm.io/gorm" +import ( + "errors" + + "gorm.io/gorm" +) type Category struct { gorm.Model @@ -11,3 +15,26 @@ type Category struct { UserID uint User *User } + +var ( + ERROR_CATEGORY_PARENT_NOT_FOUND = errors.New("ParentID is invalid for user") + ERROR_CATEGORY_NAME_NOT_UNIQUE = errors.New("Name for Category have to be unique for user") +) + +func (c *Category) BeforeSave(tx *gorm.DB) error { + var parent Category + if err := tx.Find(&parent, Category{ParentID: c.ParentID, UserID: c.UserID}).Error; err != nil { + return err + } + if parent.ID == 0 { + return ERROR_CATEGORY_PARENT_NOT_FOUND + } + var dup Category + if err := tx.Find(&dup, Category{Name: c.Name, UserID: c.UserID}).Error; err != nil { + return err + } + if dup.ID != 0 { + return ERROR_CATEGORY_NAME_NOT_UNIQUE + } + return nil +}