From 40fa706514eb82a215b236c8dc48c29cb2f43108 Mon Sep 17 00:00:00 2001 From: qowevisa Date: Sat, 3 Aug 2024 10:44:06 +0300 Subject: [PATCH] Add BeforeSave to card --- db/card.go | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/db/card.go b/db/card.go index 1685948..9d698ec 100644 --- a/db/card.go +++ b/db/card.go @@ -1,6 +1,10 @@ package db -import "gorm.io/gorm" +import ( + "errors" + + "gorm.io/gorm" +) // Card can be either card or wallet type Card struct { @@ -12,3 +16,25 @@ type Card struct { UserID uint User *User } + +var ( + ERROR_CARD_NAME_EMPTY = errors.New("Card's name can't be empty") + ERROR_CARD_NAME_NOT_UNIQUE = errors.New("Card's name have to be unique for user") +) + +func (c *Card) BeforeSave(tx *gorm.DB) error { + if c.Name == "" { + return ERROR_CARD_NAME_EMPTY + } + + var dup Card + if err := tx.Find(&dup, Card{Name: c.Name}).Error; err != nil { + return err + } + + if dup.ID != 0 { + return ERROR_CARD_NAME_NOT_UNIQUE + } + + return nil +}