api_dashboard.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package api
  2. import (
  3. log "github.com/alecthomas/log4go"
  4. "github.com/gin-gonic/gin"
  5. "github.com/torkelo/grafana-pro/pkg/models"
  6. )
  7. func init() {
  8. addRoutes(func(self *HttpServer) {
  9. self.router.GET("/api/dashboards/:slug", self.auth(), self.getDashboard)
  10. self.router.GET("/api/search/", self.auth(), self.search)
  11. self.router.POST("/api/dashboard", self.auth(), self.postDashboard)
  12. self.router.DELETE("/api/dashboard/:slug", self.auth(), self.deleteDashboard)
  13. })
  14. }
  15. func (self *HttpServer) getDashboard(c *gin.Context) {
  16. slug := c.Params.ByName("slug")
  17. accountId, err := c.Get("accountId")
  18. dash, err := self.store.GetDashboard(slug, accountId.(int))
  19. if err != nil {
  20. c.JSON(404, newErrorResponse("Dashboard not found"))
  21. return
  22. }
  23. dash.Data["id"] = dash.Id
  24. c.JSON(200, dash.Data)
  25. }
  26. func (self *HttpServer) deleteDashboard(c *gin.Context) {
  27. slug := c.Params.ByName("slug")
  28. accountId, err := c.Get("accountId")
  29. dash, err := self.store.GetDashboard(slug, accountId.(int))
  30. if err != nil {
  31. c.JSON(404, newErrorResponse("Dashboard not found"))
  32. return
  33. }
  34. err = self.store.DeleteDashboard(slug, accountId.(int))
  35. if err != nil {
  36. c.JSON(500, newErrorResponse("Failed to delete dashboard: "+err.Error()))
  37. return
  38. }
  39. var resp = map[string]interface{}{"title": dash.Title}
  40. c.JSON(200, resp)
  41. }
  42. func (self *HttpServer) search(c *gin.Context) {
  43. query := c.Params.ByName("q")
  44. accountId, err := c.Get("accountId")
  45. results, err := self.store.Query(query, accountId.(int))
  46. if err != nil {
  47. log.Error("Store query error: %v", err)
  48. c.JSON(500, newErrorResponse("Failed"))
  49. return
  50. }
  51. c.JSON(200, results)
  52. }
  53. func (self *HttpServer) postDashboard(c *gin.Context) {
  54. var command saveDashboardCommand
  55. accountId, _ := c.Get("accountId")
  56. if c.EnsureBody(&command) {
  57. dashboard := models.NewDashboard("test")
  58. dashboard.Data = command.Dashboard
  59. dashboard.Title = dashboard.Data["title"].(string)
  60. dashboard.AccountId = accountId.(int)
  61. dashboard.UpdateSlug()
  62. if dashboard.Data["id"] != nil {
  63. dashboard.Id = dashboard.Data["id"].(string)
  64. }
  65. err := self.store.SaveDashboard(dashboard)
  66. if err == nil {
  67. c.JSON(200, gin.H{"status": "success", "slug": dashboard.Slug})
  68. return
  69. }
  70. }
  71. c.JSON(500, gin.H{"error": "bad request"})
  72. }