dashboard.go 1.8 KB

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