dashboard.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package api
  2. import (
  3. "strings"
  4. "github.com/torkelo/grafana-pro/pkg/bus"
  5. "github.com/torkelo/grafana-pro/pkg/middleware"
  6. m "github.com/torkelo/grafana-pro/pkg/models"
  7. "github.com/torkelo/grafana-pro/pkg/utils"
  8. )
  9. func GetDashboard(c *middleware.Context) {
  10. slug := c.Params(":slug")
  11. query := m.GetDashboardQuery{Slug: slug, AccountId: c.GetAccountId()}
  12. err := bus.Dispatch(&query)
  13. if err != nil {
  14. c.JsonApiErr(404, "Dashboard not found", nil)
  15. return
  16. }
  17. query.Result.Data["id"] = query.Result.Id
  18. c.JSON(200, query.Result.Data)
  19. }
  20. func DeleteDashboard(c *middleware.Context) {
  21. slug := c.Params(":slug")
  22. query := m.GetDashboardQuery{Slug: slug, AccountId: c.GetAccountId()}
  23. err := bus.Dispatch(&query)
  24. if err != nil {
  25. c.JsonApiErr(404, "Dashboard not found", nil)
  26. return
  27. }
  28. cmd := m.DeleteDashboardCommand{Slug: slug, AccountId: c.GetAccountId()}
  29. err = bus.Dispatch(&cmd)
  30. if err != nil {
  31. c.JsonApiErr(500, "Failed to delete dashboard", err)
  32. return
  33. }
  34. var resp = map[string]interface{}{"title": query.Result.Title}
  35. c.JSON(200, resp)
  36. }
  37. func Search(c *middleware.Context) {
  38. queryText := c.Query("q")
  39. result := m.SearchResult{
  40. Dashboards: []m.DashboardSearchHit{},
  41. Tags: []m.DashboardTagCloudItem{},
  42. }
  43. if strings.HasPrefix(queryText, "tags!:") {
  44. query := m.GetDashboardTagsQuery{}
  45. err := bus.Dispatch(&query)
  46. if err != nil {
  47. c.JsonApiErr(500, "Failed to get tags from database", err)
  48. return
  49. }
  50. result.Tags = query.Result
  51. result.TagsOnly = true
  52. } else {
  53. queryText := strings.TrimPrefix(queryText, "title:")
  54. query := m.SearchDashboardsQuery{Query: queryText, AccountId: c.GetAccountId()}
  55. err := bus.Dispatch(&query)
  56. if err != nil {
  57. c.JsonApiErr(500, "Search failed", err)
  58. return
  59. }
  60. result.Dashboards = query.Result
  61. }
  62. c.JSON(200, result)
  63. }
  64. func PostDashboard(c *middleware.Context) {
  65. var cmd m.SaveDashboardCommand
  66. if !c.JsonBody(&cmd) {
  67. c.JsonApiErr(400, "bad request", nil)
  68. return
  69. }
  70. cmd.AccountId = c.GetAccountId()
  71. err := bus.Dispatch(&cmd)
  72. if err != nil {
  73. if err == m.ErrDashboardWithSameNameExists {
  74. c.JsonApiErr(400, "Dashboard with the same title already exists", nil)
  75. return
  76. }
  77. c.JsonApiErr(500, "Failed to save dashboard", err)
  78. return
  79. }
  80. c.JSON(200, utils.DynMap{"status": "success", "slug": cmd.Result.Slug})
  81. }