From 7d1ca772c01de568a8020290cbe258058091bd0f Mon Sep 17 00:00:00 2001 From: qowevisa Date: Thu, 31 Oct 2024 11:09:11 +0200 Subject: [PATCH] Add BeforeSave hook for type for duplicate detection --- db/type.go | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/db/type.go b/db/type.go index 3b84c7d..aec201b 100644 --- a/db/type.go +++ b/db/type.go @@ -1,10 +1,42 @@ package db -import "gorm.io/gorm" +import ( + "errors" + + "gorm.io/gorm" +) type Type struct { gorm.Model Name string Comment string Color string + UserID uint + User *User +} + +var ( + ERROR_TYPE_NAME_EMPTY = errors.New("The 'Name' field of 'Type' cannot be empty") + ERROR_TYPE_NAME_NOT_UNIQUE = errors.New("The 'Name' field of 'Type' have to be unique for user") +) + +func (t *Type) BeforeSave(tx *gorm.DB) error { + if t.Name == "" { + return ERROR_TYPE_NAME_EMPTY + } + + var dup Type + if err := tx.Find(&dup, Type{Name: t.Name, UserID: t.UserID}).Error; err != nil { + return err + } + + if t.ID != dup.ID && dup.ID != 0 { + return ERROR_TYPE_NAME_NOT_UNIQUE + } + + return nil +} + +func (t *Type) GetID() uint { + return t.ID }