From cdfd77bc210072a040a573890652d897c2ee16c6 Mon Sep 17 00:00:00 2001 From: kalipso Date: Mon, 3 Mar 2025 14:10:04 +0100 Subject: [PATCH] add tag rep --- models/tag.go | 40 +++++++++++++++++ repositories/tagRepository.go | 83 +++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 models/tag.go create mode 100644 repositories/tagRepository.go diff --git a/models/tag.go b/models/tag.go new file mode 100644 index 0000000..8ab90ab --- /dev/null +++ b/models/tag.go @@ -0,0 +1,40 @@ +package models + +import ( + "fmt" + "gorm.io/gorm" + "github.com/gin-gonic/gin" +) + +type Tag struct { + gorm.Model + Name string `json:"name" binding:"required" gorm:"unique;not null"` + ShopItems []ShopItem `gorm:"many2many:item_tags;"` +} + +func NewTag(ctx *gin.Context) (Tag, error) { + name := ctx.PostForm("name") + + // Convert the price string to float64 + tag := Tag{ + Name: name, + } + + if name == "" { + return Tag{}, fmt.Errorf("Name or description empty") + } + + return tag, nil +} + + +func NewTagByJson(ctx *gin.Context) (Tag, error) { + var tag Tag + err := ctx.ShouldBindJSON(&tag) + + if err != nil { + return Tag{}, err + } + + return tag, nil +} diff --git a/repositories/tagRepository.go b/repositories/tagRepository.go new file mode 100644 index 0000000..1a0aa2d --- /dev/null +++ b/repositories/tagRepository.go @@ -0,0 +1,83 @@ +package repositories + +import( + "strconv" + + "gorm.io/gorm" + + "example.com/gin/test/models" +) + +type TagRepository interface { + Create(models.Tag) (models.Tag, error) + GetAll() ([]models.Tag, error) + GetById(string) (models.Tag, error) + //GetByShopItemId(string) (models.Tag, error) + Update(models.Tag) (models.Tag, error) + DeleteById(string) error +} + +type GORMTagRepository struct { + DB *gorm.DB +} + +func NewGORMTagRepository(db *gorm.DB) TagRepository { + return &GORMTagRepository{ + DB: db, + } +} + +func (t *GORMTagRepository) Create(tag models.Tag) (models.Tag, error) { + result := t.DB.Create(&tag) + + if result.Error != nil { + return models.Tag{}, result.Error + } + + return tag, nil +} + + +func (t *GORMTagRepository) GetAll() ([]models.Tag, error) { + var tags []models.Tag + result := t.DB.Find(&tags) + + return tags, result.Error +} + +func (t *GORMTagRepository) GetById(id string) (models.Tag, error) { + tagId, err := strconv.Atoi(id) + + if err != nil { + return models.Tag{}, err + } + + var tag models.Tag + result := t.DB.First(&tag, uint(tagId)) + + if result.Error != nil { + return models.Tag{}, result.Error + } + + return tag, nil +} + +func (t *GORMTagRepository) Update(tag models.Tag) (models.Tag, error) { + result := t.DB.Save(&tag) + if result.Error != nil { + return models.Tag{}, result.Error + } + + return tag, nil +} + +func (t *GORMTagRepository) DeleteById(id string) error { + tagId, err := strconv.Atoi(id) + + if err != nil { + return err + } + + result := t.DB.Delete(&models.Tag{}, tagId) + return result.Error +}