dashboards.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package models
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "time"
  7. )
  8. var (
  9. GetDashboard func(slug string, accountId int64) (*Dashboard, error)
  10. DeleteDashboard func(slug string, accountId int64) error
  11. SearchQuery func(query string, acccountId int64) ([]*SearchResult, error)
  12. )
  13. // Typed errors
  14. var (
  15. ErrDashboardNotFound = errors.New("Account not found")
  16. )
  17. type Dashboard struct {
  18. Id int64
  19. Slug string `xorm:"index(IX_AccountIdSlug)"`
  20. AccountId int64 `xorm:"index(IX_AccountIdSlug)"`
  21. Created time.Time `xorm:"CREATED"`
  22. Updated time.Time `xorm:"UPDATED"`
  23. Title string
  24. Tags []string
  25. Data map[string]interface{}
  26. }
  27. type SearchResult struct {
  28. Id string `json:"id"`
  29. Title string `json:"title"`
  30. Slug string `json:"slug"`
  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. func convertToStringArray(arr []interface{}) []string {
  40. b := make([]string, len(arr))
  41. for i := range arr {
  42. b[i] = arr[i].(string)
  43. }
  44. return b
  45. }
  46. func NewDashboard(title string) *Dashboard {
  47. dash := &Dashboard{}
  48. dash.Data = make(map[string]interface{})
  49. dash.Data["title"] = title
  50. dash.Title = title
  51. dash.UpdateSlug()
  52. return dash
  53. }
  54. func (cmd *SaveDashboardCommand) GetDashboardModel() *Dashboard {
  55. dash := &Dashboard{}
  56. dash.Data = cmd.Dashboard
  57. dash.Title = dash.Data["title"].(string)
  58. dash.AccountId = cmd.AccountId
  59. dash.Tags = convertToStringArray(dash.Data["tags"].([]interface{}))
  60. dash.UpdateSlug()
  61. if dash.Data["id"] != nil {
  62. dash.Id = int64(dash.Data["id"].(float64))
  63. }
  64. return dash
  65. }
  66. func (dash *Dashboard) GetString(prop string) string {
  67. return dash.Data[prop].(string)
  68. }
  69. func (dash *Dashboard) UpdateSlug() {
  70. title := strings.ToLower(dash.Data["title"].(string))
  71. re := regexp.MustCompile("[^\\w ]+")
  72. re2 := regexp.MustCompile("\\s")
  73. dash.Slug = re2.ReplaceAllString(re.ReplaceAllString(title, ""), "-")
  74. }