category.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package service
  2. import (
  3. "fmt"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. "net/http"
  7. "sghgogs.com/micro/common"
  8. "sghgogs.com/micro/common/errorcode"
  9. req "sghgogs.com/micro/shopping-service/domain/model/request"
  10. pb "sghgogs.com/micro/shopping-service/proto"
  11. "sghgogs.com/micro/shopping-service/utils"
  12. "time"
  13. )
  14. func (svc *Service) CreateMultipleCategories(category *pb.CreateCategoryRequest) error {
  15. if err := svc.Repository.CreateMultipleCategories(svc.getCategoryReq(category)); err != nil {
  16. return errorcode.New(svc.Namespace, err.Error(), http.StatusBadRequest)
  17. }
  18. return nil
  19. }
  20. func (svc *Service) DeleteCategory(query *pb.DeleteCategoryRequest) error {
  21. if err := svc.Repository.DeleteCategory(query.CategoryId); err != nil {
  22. return errorcode.New(svc.Namespace, err.Error(), http.StatusBadRequest)
  23. }
  24. return nil
  25. }
  26. func (svc *Service) GetAllCategories() ([]*pb.Category, error) {
  27. categories := make([]*pb.Category, 0)
  28. list, err := svc.Repository.GetAllCategories()
  29. if err != nil {
  30. if errors.Is(err, gorm.ErrRecordNotFound) {
  31. return categories, nil // 记录不存在,角色不存在
  32. } else {
  33. return categories, err
  34. }
  35. }
  36. return svc.getCategoryRes(list, false), nil
  37. }
  38. func (svc *Service) GetCategoryList(query *pb.GetCategoryListRequest) ([]*pb.Category, int64, error) {
  39. categories := make([]*pb.Category, 0)
  40. list, count, err := svc.Repository.GetCategoryList(query)
  41. if err != nil {
  42. if errors.Is(err, gorm.ErrRecordNotFound) {
  43. return categories, 0, nil // 记录不存在,角色不存在
  44. } else {
  45. return categories, 0, err
  46. }
  47. }
  48. return svc.getCategoryRes(list, true), count, nil
  49. }
  50. func (svc *Service) getCategoryRes(items []req.Category, isTime bool) []*pb.Category {
  51. fmt.Println("isTime", isTime)
  52. categories := make([]*pb.Category, 0)
  53. for _, item := range items {
  54. var category *pb.Category
  55. common.SwapTo(item, &category)
  56. if isTime {
  57. category.CreatedAt = utils.ConvertTimeToInt64(item.CreatedAt)
  58. category.UpdatedAt = utils.ConvertTimeToInt64(*item.UpdatedAt)
  59. }
  60. categories = append(categories, category)
  61. }
  62. return categories
  63. }
  64. func (svc *Service) getCategoryReq(category *pb.CreateCategoryRequest) []req.Category {
  65. categories := make([]req.Category, 0)
  66. for _, item := range category.Items {
  67. categories = append(categories, req.Category{
  68. Name: item.Name,
  69. ParentCategoryID: item.ParentCategoryId,
  70. CreatedAt: time.Now(),
  71. Description: item.Description,
  72. UpdatedAt: nil,
  73. })
  74. }
  75. return categories
  76. }