share.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/service/main/share/model"
  5. "go-common/library/ecode"
  6. "go-common/library/log"
  7. "github.com/pkg/errors"
  8. )
  9. // Shares get shares
  10. func (d *Dao) Shares(ctx context.Context, oids []int64, tp int) (shares map[int64]int64, err error) {
  11. shares, err = d.SharesCache(ctx, oids, tp)
  12. if err != nil {
  13. log.Error("d.SharesCache(%v) tp(%d) error(%v)", oids, tp, err)
  14. err = nil
  15. shares = make(map[int64]int64, len(oids))
  16. }
  17. var missed []int64
  18. for _, oid := range oids {
  19. if _, ok := shares[oid]; !ok {
  20. missed = append(missed, oid)
  21. }
  22. }
  23. if len(missed) == 0 {
  24. return
  25. }
  26. // 最大30个id,并且分了100张表,用in的优化空间也不大,暂时循环单个查
  27. for _, oid := range missed {
  28. cnt, err := d.ShareCount(ctx, oid, tp)
  29. if err != nil {
  30. continue
  31. }
  32. shares[oid] = cnt
  33. }
  34. return
  35. }
  36. // ShareCount get share from cache/db
  37. func (d *Dao) ShareCount(ctx context.Context, oid int64, tp int) (count int64, err error) {
  38. count, err = d.ShareCache(ctx, oid, tp)
  39. if count != -1 && err == nil {
  40. return
  41. }
  42. var share *model.Share
  43. if share, err = d.Share(ctx, oid, tp); err != nil {
  44. err = errors.WithStack(err)
  45. return
  46. }
  47. count = 0
  48. if share != nil {
  49. count = share.Count
  50. }
  51. d.asyncCache.Save(func() {
  52. if err = d.SetShareCache(context.Background(), oid, tp, count); err != nil {
  53. log.Error("%+v", err)
  54. return
  55. }
  56. })
  57. return
  58. }
  59. // Add add share
  60. func (d *Dao) Add(ctx context.Context, p *model.ShareParams) (shared int64, err error) {
  61. var ok bool
  62. if ok, err = d.AddShareMember(ctx, p); err != nil {
  63. return
  64. }
  65. if !ok {
  66. err = ecode.ShareAlreadyAdd
  67. return
  68. }
  69. if err = d.AddShare(ctx, p.OID, p.TP); err != nil {
  70. err = errors.WithStack(err)
  71. return
  72. }
  73. var share *model.Share
  74. if share, err = d.Share(ctx, p.OID, p.TP); err != nil {
  75. err = errors.WithStack(err)
  76. return
  77. }
  78. shared = share.Count
  79. d.asyncCache.Save(func() {
  80. if err = d.SetShareCache(context.Background(), p.OID, p.TP, shared); err != nil {
  81. log.Error("%+v", err)
  82. return
  83. }
  84. })
  85. return
  86. }