api_config.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package api
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "github.com/torkelo/grafana-pro/pkg/bus"
  6. "github.com/torkelo/grafana-pro/pkg/middleware"
  7. m "github.com/torkelo/grafana-pro/pkg/models"
  8. )
  9. const configTemplate = `
  10. define(['settings'],
  11. function (Settings) {
  12. "use strict";
  13. return new Settings(%json%);
  14. });
  15. `
  16. type configJsTmplModel struct {
  17. DataSources []*m.DataSource
  18. }
  19. func renderConfig(data *configJsTmplModel) string {
  20. datasources := make(map[string]interface{})
  21. for _, ds := range data.DataSources {
  22. datasources[ds.Name] = map[string]interface{}{
  23. "type": ds.Type,
  24. "url": ds.Url,
  25. }
  26. }
  27. jsonObj := map[string]interface{}{
  28. "datasources": datasources,
  29. }
  30. buff, _ := json.Marshal(jsonObj)
  31. return strings.Replace(configTemplate, "%json%", string(buff), 1)
  32. }
  33. func GetConfigJS(c *middleware.Context) {
  34. query := m.GetDataSourcesQuery{AccountId: c.GetAccountId()}
  35. err := bus.Dispatch(&query)
  36. if err != nil {
  37. c.Handle(500, "cold not load data sources", err)
  38. return
  39. }
  40. vm := configJsTmplModel{DataSources: query.Result}
  41. configStr := renderConfig(&vm)
  42. if err != nil {
  43. c.Handle(500, "Failed to generate config.js", err)
  44. return
  45. }
  46. c.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
  47. c.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  48. c.Header().Set("Pragma", "no-cache")
  49. c.Header().Set("Expires", "0")
  50. c.WriteHeader(200)
  51. c.Write([]byte(configStr))
  52. }