api_datasources.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. User: ds.User,
  26. BasicAuth: ds.BasicAuth,
  27. }
  28. }
  29. c.JSON(200, result)
  30. }
  31. func DeleteDataSource(c *middleware.Context) {
  32. id := c.ParamsInt64(":id")
  33. if id <= 0 {
  34. c.JsonApiErr(400, "Missing valid datasource id", nil)
  35. return
  36. }
  37. cmd := &m.DeleteDataSourceCommand{Id: id, AccountId: c.UserAccount.Id}
  38. err := bus.Dispatch(cmd)
  39. if err != nil {
  40. c.JsonApiErr(500, "Failed to delete datasource", err)
  41. return
  42. }
  43. c.JsonOK("Data source deleted")
  44. }
  45. func AddDataSource(c *middleware.Context) {
  46. cmd := m.AddDataSourceCommand{}
  47. if !c.JsonBody(&cmd) {
  48. c.JsonApiErr(400, "Validation failed", nil)
  49. return
  50. }
  51. cmd.AccountId = c.Account.Id
  52. err := bus.Dispatch(&cmd)
  53. if err != nil {
  54. c.JsonApiErr(500, "Failed to add datasource", err)
  55. return
  56. }
  57. c.JsonOK("Datasource added")
  58. }
  59. func UpdateDataSource(c *middleware.Context) {
  60. cmd := m.UpdateDataSourceCommand{}
  61. if !c.JsonBody(&cmd) {
  62. c.JsonApiErr(400, "Validation failed", nil)
  63. return
  64. }
  65. cmd.AccountId = c.Account.Id
  66. err := bus.Dispatch(&cmd)
  67. if err != nil {
  68. c.JsonApiErr(500, "Failed to update datasource", err)
  69. return
  70. }
  71. c.JsonOK("Datasource updated")
  72. }