dashboards.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package models
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "time"
  7. )
  8. // Typed errors
  9. var (
  10. ErrDashboardNotFound = errors.New("Account not found")
  11. )
  12. type Dashboard struct {
  13. Id int64
  14. Slug string `xorm:"index(IX_AccountIdSlug)"`
  15. AccountId int64 `xorm:"index(IX_AccountIdSlug)"`
  16. Created time.Time `xorm:"CREATED"`
  17. Updated time.Time `xorm:"UPDATED"`
  18. Title string
  19. Tags []string
  20. Data map[string]interface{}
  21. }
  22. type SearchResult struct {
  23. Id string `json:"id"`
  24. Title string `json:"title"`
  25. Slug string `json:"slug"`
  26. }
  27. type SearchDashboardsQuery struct {
  28. Query string
  29. AccountId int64
  30. Result []*SearchResult
  31. }
  32. type SaveDashboardCommand struct {
  33. Id string `json:"id"`
  34. Title string `json:"title"`
  35. Dashboard map[string]interface{} `json:"dashboard"`
  36. AccountId int64 `json:"-"`
  37. Result *Dashboard
  38. }
  39. type DeleteDashboardCommand struct {
  40. Slug string
  41. AccountId int64
  42. }
  43. type GetDashboardQuery struct {
  44. Slug string
  45. AccountId int64
  46. Result *Dashboard
  47. }
  48. func convertToStringArray(arr []interface{}) []string {
  49. b := make([]string, len(arr))
  50. for i := range arr {
  51. b[i] = arr[i].(string)
  52. }
  53. return b
  54. }
  55. func NewDashboard(title string) *Dashboard {
  56. dash := &Dashboard{}
  57. dash.Data = make(map[string]interface{})
  58. dash.Data["title"] = title
  59. dash.Title = title
  60. dash.UpdateSlug()
  61. return dash
  62. }
  63. func (cmd *SaveDashboardCommand) GetDashboardModel() *Dashboard {
  64. dash := &Dashboard{}
  65. dash.Data = cmd.Dashboard
  66. dash.Title = dash.Data["title"].(string)
  67. dash.AccountId = cmd.AccountId
  68. dash.Tags = convertToStringArray(dash.Data["tags"].([]interface{}))
  69. dash.UpdateSlug()
  70. if dash.Data["id"] != nil {
  71. dash.Id = int64(dash.Data["id"].(float64))
  72. }
  73. return dash
  74. }
  75. func (dash *Dashboard) GetString(prop string) string {
  76. return dash.Data[prop].(string)
  77. }
  78. func (dash *Dashboard) UpdateSlug() {
  79. title := strings.ToLower(dash.Data["title"].(string))
  80. re := regexp.MustCompile("[^\\w ]+")
  81. re2 := regexp.MustCompile("\\s")
  82. dash.Slug = re2.ReplaceAllString(re.ReplaceAllString(title, ""), "-")
  83. }