dao.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/service/main/workflow/conf"
  5. "go-common/app/service/main/workflow/model"
  6. "go-common/library/database/elastic"
  7. "go-common/library/database/orm"
  8. "go-common/library/log"
  9. bm "go-common/library/net/http/blademaster"
  10. "github.com/jinzhu/gorm"
  11. )
  12. const (
  13. _mngTagURL = "/x/admin/manager/internal/tag/list"
  14. _mngControlURL = "/x/admin/manager/internal/control/list"
  15. )
  16. // Dao tag dao
  17. type Dao struct {
  18. c *conf.Config
  19. // db *sql.DB
  20. DB *gorm.DB
  21. callback *bm.Client
  22. callbackMap map[int8]string
  23. ReadClient *bm.Client
  24. MngTagURL string
  25. MngControlURL string
  26. es *elastic.Elastic
  27. }
  28. // New init dao
  29. func New(c *conf.Config) (d *Dao) {
  30. d = &Dao{
  31. c: c,
  32. DB: orm.NewMySQL(c.ORM.Write),
  33. callback: bm.NewClient(c.HTTPClient.Write),
  34. callbackMap: make(map[int8]string),
  35. ReadClient: bm.NewClient(c.HTTPClient.Read),
  36. MngTagURL: c.Host.ManagerURI + _mngTagURL,
  37. MngControlURL: c.Host.ManagerURI + _mngControlURL,
  38. es: elastic.NewElastic(c.Elastic),
  39. }
  40. d.initORM()
  41. d.initCallback()
  42. return
  43. }
  44. func (d *Dao) initORM() {
  45. d.DB.LogMode(true)
  46. }
  47. func (d *Dao) initCallback() {
  48. callbacks := []model.Callback{}
  49. if err := d.DB.Where("state =?", model.Enabled).Find(&callbacks).Error; err != nil {
  50. log.Error("d.CallbackSetting() error(%v)", err)
  51. panic(err)
  52. }
  53. for _, callback := range callbacks {
  54. d.callbackMap[callback.Business] = callback.URL
  55. }
  56. }
  57. // Close close dao.
  58. func (d *Dao) Close() {
  59. if d.DB != nil {
  60. d.DB.Close()
  61. }
  62. }
  63. // Ping ping cpdb
  64. func (d *Dao) Ping(c context.Context) (err error) {
  65. if d.DB != nil {
  66. err = d.DB.DB().PingContext(c)
  67. }
  68. return
  69. }