From 520ed8f6387e0744a21a52912418e3acb08d18a5 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 3 Sep 2023 19:18:27 +0530 Subject: different brands and items for different users --- item/service.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'item/service.go') diff --git a/item/service.go b/item/service.go index c8a72f6..fb03adc 100644 --- a/item/service.go +++ b/item/service.go @@ -22,12 +22,12 @@ import ( e "vidhukant.com/openbills/errors" ) -func getBrandItems(items *[]SavedItem, id uint) error { - // check if id is valid +func getBrandItems(items *[]SavedItem, id, userId uint) error { + // check if brand id is valid and is owned by user var count int64 err := db.Model(&Brand{}). Select("id"). - Where("id = ?", id). + Where("id = ? and user_id = ?", id, userId). Count(&count). Error @@ -46,6 +46,7 @@ func getBrandItems(items *[]SavedItem, id uint) error { return res.Error } + // returns 404 if either row doesn't exist or if the user doesn't own it if res.RowsAffected == 0 { return e.ErrEmptyResponse } @@ -53,8 +54,8 @@ func getBrandItems(items *[]SavedItem, id uint) error { return nil } -func getBrands(brands *[]Brand) error { - res := db.Find(&brands) +func getBrands(brands *[]Brand, userId uint) error { + res := db.Where("user_id = ?", userId).Find(&brands) // TODO: handle potential errors if res.Error != nil { @@ -74,14 +75,16 @@ func (b *Brand) upsert() error { return res.Error } +// TODO: delete all items upon brand deletion func (b *Brand) del() error { - res := db.Delete(b) + res := db.Where("id = ? and user_id = ?", b.ID, b.UserID).Delete(b) // TODO: handle potential errors if res.Error != nil { return res.Error } + // returns 404 if either row doesn't exist or if the user doesn't own it if res.RowsAffected == 0 { return e.ErrNotFound } @@ -89,8 +92,8 @@ func (b *Brand) del() error { return nil } -func getItems(items *[]SavedItem) error { - res := db.Preload("Brand").Find(&items) +func getItems(items *[]SavedItem, userId uint) error { + res := db.Where("user_id = ?", userId).Preload("Brand").Find(&items) // TODO: handle potential errors if res.Error != nil { @@ -111,13 +114,14 @@ func (i *SavedItem) upsert() error { } func (i *SavedItem) del() error { - res := db.Delete(i) + res := db.Where("id = ? and user_id = ?", i.ID, i.UserID).Delete(i) // TODO: handle potential errors if res.Error != nil { return res.Error } + // returns 404 if either row doesn't exist or if the user doesn't own it if res.RowsAffected == 0 { return e.ErrNotFound } -- cgit v1.2.3