search.go 1.8 KB

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