dashboards.go 2.1 KB

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