datasources.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package api
  2. import (
  3. "github.com/torkelo/grafana-pro/pkg/api/dtos"
  4. "github.com/torkelo/grafana-pro/pkg/bus"
  5. "github.com/torkelo/grafana-pro/pkg/middleware"
  6. m "github.com/torkelo/grafana-pro/pkg/models"
  7. )
  8. func GetDataSources(c *middleware.Context) {
  9. query := m.GetDataSourcesQuery{AccountId: c.Account.Id}
  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. }
  29. }
  30. c.JSON(200, result)
  31. }
  32. func DeleteDataSource(c *middleware.Context) {
  33. id := c.ParamsInt64(":id")
  34. if id <= 0 {
  35. c.JsonApiErr(400, "Missing valid datasource id", nil)
  36. return
  37. }
  38. cmd := &m.DeleteDataSourceCommand{Id: id, AccountId: c.UserAccount.Id}
  39. err := bus.Dispatch(cmd)
  40. if err != nil {
  41. c.JsonApiErr(500, "Failed to delete datasource", err)
  42. return
  43. }
  44. c.JsonOK("Data source deleted")
  45. }
  46. func AddDataSource(c *middleware.Context) {
  47. cmd := m.AddDataSourceCommand{}
  48. if !c.JsonBody(&cmd) {
  49. c.JsonApiErr(400, "Validation failed", nil)
  50. return
  51. }
  52. cmd.AccountId = c.Account.Id
  53. if err := bus.Dispatch(&cmd); err != nil {
  54. c.JsonApiErr(500, "Failed to add datasource", err)
  55. return
  56. }
  57. //bus.Publish(&m.DataSourceCreatedEvent{Account: c.GetAccountId(), })
  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.Account.Id
  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. }