api_dashboard.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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/:id", 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. })
  13. }
  14. func (self *HttpServer) getDashboard(c *gin.Context) {
  15. id := c.Params.ByName("id")
  16. accountId, err := c.Get("accountId")
  17. dash, err := self.store.GetDashboard(id, accountId.(int))
  18. if err != nil {
  19. c.JSON(404, newErrorResponse("Dashboard not found"))
  20. return
  21. }
  22. c.JSON(200, dash.Data)
  23. }
  24. func (self *HttpServer) search(c *gin.Context) {
  25. query := c.Params.ByName("q")
  26. accountId, err := c.Get("accountId")
  27. results, err := self.store.Query(query, accountId.(int))
  28. if err != nil {
  29. log.Error("Store query error: %v", err)
  30. c.JSON(500, newErrorResponse("Failed"))
  31. return
  32. }
  33. c.JSON(200, results)
  34. }
  35. func (self *HttpServer) postDashboard(c *gin.Context) {
  36. var command saveDashboardCommand
  37. accountId, _ := c.Get("accountId")
  38. if c.EnsureBody(&command) {
  39. dashboard := models.NewDashboard("test")
  40. dashboard.Data = command.Dashboard
  41. dashboard.Title = dashboard.Data["title"].(string)
  42. dashboard.AccountId = accountId.(int)
  43. dashboard.UpdateSlug()
  44. if dashboard.Data["id"] != nil {
  45. dashboard.Id = dashboard.Data["id"].(string)
  46. }
  47. err := self.store.SaveDashboard(dashboard)
  48. if err == nil {
  49. c.JSON(200, gin.H{"status": "success", "slug": dashboard.Slug})
  50. return
  51. }
  52. }
  53. c.JSON(500, gin.H{"error": "bad request"})
  54. }