datasources.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/middleware"
  6. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. func GetDataSources(c *middleware.Context) {
  9. query := m.GetDataSourcesQuery{AccountId: c.AccountId}
  10. err := bus.Dispatch(&query)
  11. if err != nil {
  12. c.JsonApiErr(500, "Failed to query datasources", err)
  13. return
  14. }
  15. result := make([]*dtos.DataSource, len(query.Result))
  16. for i, ds := range query.Result {
  17. result[i] = &dtos.DataSource{
  18. Id: ds.Id,
  19. AccountId: ds.AccountId,
  20. Name: ds.Name,
  21. Url: ds.Url,
  22. Type: ds.Type,
  23. Access: ds.Access,
  24. Password: ds.Password,
  25. Database: ds.Database,
  26. User: ds.User,
  27. BasicAuth: ds.BasicAuth,
  28. IsDefault: ds.IsDefault,
  29. }
  30. }
  31. c.JSON(200, result)
  32. }
  33. func DeleteDataSource(c *middleware.Context) {
  34. id := c.ParamsInt64(":id")
  35. if id <= 0 {
  36. c.JsonApiErr(400, "Missing valid datasource id", nil)
  37. return
  38. }
  39. cmd := &m.DeleteDataSourceCommand{Id: id, AccountId: c.AccountId}
  40. err := bus.Dispatch(cmd)
  41. if err != nil {
  42. c.JsonApiErr(500, "Failed to delete datasource", err)
  43. return
  44. }
  45. c.JsonOK("Data source deleted")
  46. }
  47. func AddDataSource(c *middleware.Context) {
  48. cmd := m.AddDataSourceCommand{}
  49. if !c.JsonBody(&cmd) {
  50. c.JsonApiErr(400, "Validation failed", nil)
  51. return
  52. }
  53. cmd.AccountId = c.AccountId
  54. if err := bus.Dispatch(&cmd); err != nil {
  55. c.JsonApiErr(500, "Failed to add datasource", err)
  56. return
  57. }
  58. c.JsonOK("Datasource added")
  59. }
  60. func UpdateDataSource(c *middleware.Context) {
  61. cmd := m.UpdateDataSourceCommand{}
  62. if !c.JsonBody(&cmd) {
  63. c.JsonApiErr(400, "Validation failed", nil)
  64. return
  65. }
  66. cmd.AccountId = c.AccountId
  67. err := bus.Dispatch(&cmd)
  68. if err != nil {
  69. c.JsonApiErr(500, "Failed to update datasource", err)
  70. return
  71. }
  72. c.JsonOK("Datasource updated")
  73. }