diff --git a/internal/api/merch/dto.go b/internal/api/merch/dto.go index 32e72e4..ad63c26 100644 --- a/internal/api/merch/dto.go +++ b/internal/api/merch/dto.go @@ -27,8 +27,9 @@ type SingleMerchResponse struct { } type ListResponse struct { - MerchUuid string `json:"merch_uuid"` - Name string `json:"name"` + MerchUuid string `json:"merch_uuid"` + Name string `json:"name"` + Labels []string `json:"labels,omitempty" gorm:"-"` } type PriceEntry struct { diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index 5b3c308..d1567de 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -47,6 +47,7 @@ type labels interface { deleteLabel(userUuid, labelUuid string) error attachLabel(label CardLabel) error detachLabel(label CardLabel) error + getAttachedLabelsByList(list []string) ([]CardLabel, error) } func (r *Repo) addMerch(bundle merchBundle) error { @@ -289,3 +290,13 @@ func (r *Repo) detachLabel(label CardLabel) error { Where("user_uuid = ? AND label_uuid = ? AND merch_uuid = ?", label.UserUuid, label.LabelUuid, label.MerchUuid). Delete(&CardLabel{}).Error } + +func (r *Repo) getAttachedLabelsByList(list []string) ([]CardLabel, error) { + var labelsList []CardLabel + + if err := r.db.Model(&CardLabel{}).Where("merch_uuid IN ?", list).Find(&labelsList).Error; err != nil { + return nil, err + } + + return labelsList, nil +} diff --git a/internal/api/merch/service.go b/internal/api/merch/service.go index c6902ff..1632329 100644 --- a/internal/api/merch/service.go +++ b/internal/api/merch/service.go @@ -101,7 +101,34 @@ func (s *service) getSingleMerch(userUuid, merchUuid string) (MerchDTO, error) { } func (s *service) getAllMerch(userUuid string) ([]ListResponse, error) { - return s.repo.getAllMerch(userUuid) + const logMsg = "Merch service | Get all merch" + + allMerch, err := s.repo.getAllMerch(userUuid) + if err != nil { + return nil, err + } + + ids := make([]string, 0, len(allMerch)) + for _, m := range allMerch { + ids = append(ids, m.MerchUuid) + } + + cardLabels, err := s.repo.getAttachedLabelsByList(ids) + if err != nil { + return nil, err + } + log.WithField("content", cardLabels).Debug(logMsg) + + clMap := make(map[string][]string) + for _, cl := range cardLabels { + clMap[cl.MerchUuid] = append(clMap[cl.MerchUuid], cl.LabelUuid) + } + + for item := range allMerch { + allMerch[item].Labels = clMap[allMerch[item].MerchUuid] + } + + return allMerch, nil } func (s *service) updateMerch(payload UpdateMerchDTO, userUuid string) error {