crud_time.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package fire
  2. import (
  3. "time"
  4. "cloud.google.com/go/firestore"
  5. )
  6. type cudTime struct {
  7. Time time.Time
  8. TimeSec int64
  9. }
  10. // newCudTime returns a new newCudTime pointer
  11. func NewCudTime() *cudTime {
  12. now, _ := NowMM()
  13. sec := TimestampMilli(*now)
  14. return &cudTime{Time: *now, TimeSec: sec}
  15. }
  16. func (up *cudTime) toMapForCreate() map[string]interface{} {
  17. val := make(map[string]interface{})
  18. val["delete_time"] = 0
  19. val["is_deleted"] = false
  20. val["update_time"] = up.TimeSec
  21. val["updated_date"] = up.Time
  22. val["created_date"] = up.Time
  23. return val
  24. }
  25. func (up *cudTime) toMapForUpdate() map[string]interface{} {
  26. val := make(map[string]interface{})
  27. val["update_time"] = up.TimeSec
  28. val["updated_date"] = up.Time
  29. return val
  30. }
  31. func (up *cudTime) toMapForDelete() map[string]interface{} {
  32. val := make(map[string]interface{})
  33. val["is_deleted"] = true
  34. val["update_time"] = up.TimeSec
  35. val["delete_time"] = up.TimeSec
  36. val["updated_date"] = up.Time
  37. val["deleted_date"] = up.Time
  38. return val
  39. }
  40. func (up *cudTime) C(tx *firestore.Transaction, docRefs ...*firestore.DocumentRef) error {
  41. return up._op(tx, up.toMapForCreate(), docRefs...)
  42. }
  43. func (up *cudTime) U(tx *firestore.Transaction, docRefs ...*firestore.DocumentRef) error {
  44. return up._op(tx, up.toMapForUpdate(), docRefs...)
  45. }
  46. func (up *cudTime) D(tx *firestore.Transaction, docRefs ...*firestore.DocumentRef) error {
  47. return up._op(tx, up.toMapForDelete(), docRefs...)
  48. }
  49. func (up *cudTime) _op(tx *firestore.Transaction, data map[string]interface{}, docRefs ...*firestore.DocumentRef) error {
  50. if len(docRefs) <= 0 {
  51. return nil
  52. }
  53. for _, docRef := range docRefs {
  54. if err := tx.Set(docRef, data, firestore.MergeAll); err != nil {
  55. return err
  56. }
  57. }
  58. return nil
  59. }