search.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/bus"
  4. "github.com/grafana/grafana/pkg/middleware"
  5. m "github.com/grafana/grafana/pkg/models"
  6. )
  7. // TODO: this needs to be cached or improved somehow
  8. func setIsStarredFlagOnSearchResults(c *middleware.Context, hits []*m.DashboardSearchHit) error {
  9. if !c.IsSignedIn {
  10. return nil
  11. }
  12. query := m.GetUserStarsQuery{UserId: c.UserId}
  13. if err := bus.Dispatch(&query); err != nil {
  14. return err
  15. }
  16. for _, dash := range hits {
  17. if _, exists := query.Result[dash.Id]; exists {
  18. dash.IsStarred = true
  19. }
  20. }
  21. return nil
  22. }
  23. func Search(c *middleware.Context) {
  24. query := c.Query("query")
  25. tag := c.Query("tag")
  26. tagcloud := c.Query("tagcloud")
  27. starred := c.Query("starred")
  28. limit := c.QueryInt("limit")
  29. if limit == 0 {
  30. limit = 200
  31. }
  32. result := m.SearchResult{
  33. Dashboards: []*m.DashboardSearchHit{},
  34. Tags: []*m.DashboardTagCloudItem{},
  35. }
  36. if tagcloud == "true" {
  37. query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
  38. err := bus.Dispatch(&query)
  39. if err != nil {
  40. c.JsonApiErr(500, "Failed to get tags from database", err)
  41. return
  42. }
  43. result.Tags = query.Result
  44. result.TagsOnly = true
  45. } else {
  46. query := m.SearchDashboardsQuery{
  47. Title: query,
  48. Tag: tag,
  49. UserId: c.UserId,
  50. Limit: limit,
  51. IsStarred: starred == "true",
  52. OrgId: c.OrgId,
  53. }
  54. err := bus.Dispatch(&query)
  55. if err != nil {
  56. c.JsonApiErr(500, "Search failed", err)
  57. return
  58. }
  59. if err := setIsStarredFlagOnSearchResults(c, query.Result); err != nil {
  60. c.JsonApiErr(500, "Failed to get user stars", err)
  61. return
  62. }
  63. result.Dashboards = query.Result
  64. }
  65. c.JSON(200, result)
  66. }