shop.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package shop
  2. import (
  3. "errors"
  4. "zhiyuan/models"
  5. "zhiyuan/pkg/db"
  6. "zhiyuan/pkg/redis"
  7. "zhiyuan/pkg/utils"
  8. "zhiyuan/services/form"
  9. )
  10. var Shop models.Shop
  11. const cacheKey = "shop"
  12. func GetList(where map[string]interface{}, fields []string, retVal interface{}) ([]*models.Shop, error) {
  13. return Shop.GetMulti(where, fields, retVal)
  14. }
  15. func GetListByCache() ([]*models.Shop, error) {
  16. res, err := redis.Get(cacheKey)
  17. var shopList []*models.Shop
  18. if err != nil {
  19. shopList, err = GetList(nil, nil, nil)
  20. if err != nil {
  21. return nil, err
  22. }
  23. redis.Set(cacheKey, shopList, 3600)
  24. } else {
  25. utils.JsonDecode(res).To(&shopList)
  26. }
  27. return shopList, nil
  28. }
  29. func Add(form form.ShopAdd) (int64, error) {
  30. if CheckDuplicate(form.ShopName) {
  31. return 0, errors.New("门店已存在")
  32. }
  33. shopMap := map[string]interface{}{
  34. "shop_name": form.ShopName,
  35. "collect_info": form.CollectInfo,
  36. }
  37. shopID, err := db.InsertOne(Shop.TableName(), shopMap)
  38. if err != nil {
  39. return 0, nil
  40. }
  41. redis.Del(cacheKey)
  42. return shopID, nil
  43. }
  44. func Edit(form form.ShopAdd, id int) (int64, error) {
  45. shopInfo, _ := GetOne(map[string]interface{}{"id": id}, nil, nil)
  46. if shopInfo.ShopName != form.ShopName && CheckDuplicate(form.ShopName) {
  47. return 0, errors.New("门店已存在")
  48. }
  49. shopMap := map[string]interface{}{
  50. "shop_name": form.ShopName,
  51. "collect_info": form.CollectInfo,
  52. }
  53. redis.Del(cacheKey)
  54. return db.Update(Shop.TableName(), map[string]interface{}{"id": id}, shopMap)
  55. }
  56. func GetOne(where map[string]interface{}, fields []string, dest interface{}) (*models.Shop, error) {
  57. return Shop.GetOne(where, fields, dest)
  58. }
  59. func CheckDuplicate(name string) bool {
  60. shopInfo, err := GetOne(map[string]interface{}{"shop_name": name}, nil, nil)
  61. return shopInfo != nil && err == nil
  62. }