neighbor_class_add.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package neighbor
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "property-garden/impl/v1/oss_utils"
  9. "strings"
  10. "property-garden/errors"
  11. dbmodel "property-garden/model"
  12. pb_v1 "property-garden/pb/v1"
  13. "property-garden/utils"
  14. "time"
  15. "git.getensh.com/common/gopkgs/database"
  16. "git.getensh.com/common/gopkgs/logger"
  17. "go.uber.org/zap"
  18. "google.golang.org/grpc/status"
  19. )
  20. func checkNeighborClassAddParam(req *pb_v1.NeighborClassAddRequest) error {
  21. switch {
  22. case req.GardenId == 0:
  23. return status.Error(10003, "小区不能为空")
  24. case req.ClassName == "":
  25. return status.Error(10003, "名称不能为空")
  26. case len(req.ClassName) > 128:
  27. return status.Error(10003, "分类名过长")
  28. }
  29. return nil
  30. }
  31. func NeighborClassAdd(ctx context.Context, req *pb_v1.NeighborClassAddRequest) (reply *pb_v1.NeighborClassAddReply, err error) {
  32. reply = &pb_v1.NeighborClassAddReply{}
  33. // 捕获各个task中的异常并返回给调用者
  34. defer func() {
  35. if r := recover(); r != nil {
  36. err = fmt.Errorf("%+v", r)
  37. e := &status.Status{}
  38. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  39. logger.Error("err",
  40. zap.String("system_err", err.Error()),
  41. zap.Stack("stacktrace"))
  42. }
  43. }
  44. }()
  45. // 参数检查
  46. err = checkNeighborClassAddParam(req)
  47. if err != nil {
  48. return nil, err
  49. }
  50. now := time.Now()
  51. dbname := utils.GetGardenDbName(req.GardenId)
  52. enable := int32(1)
  53. if !req.Enable {
  54. enable = 2
  55. }
  56. p := dbmodel.TNeighborClass{
  57. ClassName:req.ClassName,
  58. Enable:enable,
  59. UpdatedAt:now,
  60. CreatedAt:now,
  61. ClassPic:req.ClassPic,
  62. }
  63. p.SetTable(dbname)
  64. db := database.DB().Begin()
  65. err = p.Insert(db)
  66. if err != nil {
  67. db.Rollback()
  68. if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  69. return nil, status.Error(10003, "分类名已存在")
  70. }
  71. return nil, errors.DataBaseError
  72. }
  73. if err := oss_utils.OssObjAdd([]string{req.ClassPic}, nil); err != nil {
  74. db.Rollback()
  75. return nil, err
  76. }
  77. db.Commit()
  78. return reply, nil
  79. }