api_config.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "github.com/torkelo/grafana-pro/pkg/bus"
  7. "github.com/torkelo/grafana-pro/pkg/middleware"
  8. m "github.com/torkelo/grafana-pro/pkg/models"
  9. )
  10. const configTemplate = `
  11. define(['settings'],
  12. function (Settings) {
  13. "use strict";
  14. return new Settings(%json%);
  15. });
  16. `
  17. type configJsTmplModel struct {
  18. DataSources []*m.DataSource
  19. }
  20. // TODO: cleanup this ugly code
  21. func renderConfig(data *configJsTmplModel) string {
  22. datasources := make(map[string]interface{})
  23. for i, ds := range data.DataSources {
  24. url := ds.Url
  25. if ds.Access == m.DS_ACCESS_PROXY {
  26. url = "/api/datasources/proxy/" + strconv.FormatInt(ds.Id, 10)
  27. }
  28. var dsMap = map[string]interface{}{
  29. "type": ds.Type,
  30. "url": url,
  31. }
  32. // temp hack, first is always default
  33. // TODO: implement default ds account setting
  34. if i == 0 {
  35. dsMap["default"] = true
  36. }
  37. datasources[ds.Name] = dsMap
  38. }
  39. // add grafana backend data source
  40. datasources["grafana"] = map[string]interface{}{
  41. "type": "grafana",
  42. "url": "",
  43. "grafanaDB": true,
  44. }
  45. jsonObj := map[string]interface{}{
  46. "datasources": datasources,
  47. }
  48. buff, _ := json.Marshal(jsonObj)
  49. return strings.Replace(configTemplate, "%json%", string(buff), 1)
  50. }
  51. func GetConfigJS(c *middleware.Context) {
  52. query := m.GetDataSourcesQuery{AccountId: c.GetAccountId()}
  53. err := bus.Dispatch(&query)
  54. if err != nil {
  55. c.Handle(500, "cold not load data sources", err)
  56. return
  57. }
  58. vm := configJsTmplModel{DataSources: query.Result}
  59. configStr := renderConfig(&vm)
  60. if err != nil {
  61. c.Handle(500, "Failed to generate config.js", err)
  62. return
  63. }
  64. c.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
  65. c.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  66. c.Header().Set("Pragma", "no-cache")
  67. c.Header().Set("Expires", "0")
  68. c.WriteHeader(200)
  69. c.Write([]byte(configStr))
  70. }