refactor(): refactoring json usage

This commit is contained in:
Torkel Ödegaard
2016-03-12 00:13:06 +01:00
parent 40b2f00dc5
commit 3fb0b71822
8 changed files with 68 additions and 86 deletions

View File

@ -6,7 +6,7 @@ import (
"regexp"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/dynmap"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models"
)
@ -54,9 +54,8 @@ func ImportDashboard(cmd *ImportDashboardCommand) error {
return err
}
template := dynmap.NewFromMap(dashboard.Data)
evaluator := &DashTemplateEvaluator{
template: template,
template: dashboard.Data,
inputs: cmd.Inputs,
}
@ -66,7 +65,7 @@ func ImportDashboard(cmd *ImportDashboardCommand) error {
}
saveCmd := m.SaveDashboardCommand{
Dashboard: generatedDash.StringMap(),
Dashboard: generatedDash,
OrgId: cmd.OrgId,
UserId: cmd.UserId,
}
@ -89,15 +88,15 @@ func ImportDashboard(cmd *ImportDashboardCommand) error {
}
type DashTemplateEvaluator struct {
template *dynmap.Object
template *simplejson.Json
inputs []ImportDashboardInput
variables map[string]string
result *dynmap.Object
result *simplejson.Json
varRegex *regexp.Regexp
}
func (this *DashTemplateEvaluator) findInput(varName string, varDef *dynmap.Object) *ImportDashboardInput {
inputType, _ := varDef.GetString("type")
func (this *DashTemplateEvaluator) findInput(varName string, varDef *simplejson.Json) *ImportDashboardInput {
inputType := varDef.Get("type").MustString()
for _, input := range this.inputs {
if inputType == input.Type && (input.Name == varName || input.Name == "*") {
@ -108,16 +107,15 @@ func (this *DashTemplateEvaluator) findInput(varName string, varDef *dynmap.Obje
return nil
}
func (this *DashTemplateEvaluator) Eval() (*dynmap.Object, error) {
this.result = dynmap.NewObject()
func (this *DashTemplateEvaluator) Eval() (*simplejson.Json, error) {
this.result = simplejson.New()
this.variables = make(map[string]string)
this.varRegex, _ = regexp.Compile("\\$__(\\w+)")
// check that we have all inputs we need
if requiredInputs, err := this.template.GetObject("__inputs"); err == nil {
for varName, value := range requiredInputs.Map() {
varDef, _ := value.Object()
input := this.findInput(varName, varDef)
if inputDefs := this.template.Get("__inputs"); inputDefs != nil {
for varName, value := range inputDefs.MustMap() {
input := this.findInput(varName, simplejson.NewFromAny(value))
if input == nil {
return nil, &DashboardInputMissingError{VariableName: varName}
@ -133,28 +131,28 @@ func (this *DashTemplateEvaluator) Eval() (*dynmap.Object, error) {
return this.result, nil
}
func (this *DashTemplateEvaluator) EvalObject(source *dynmap.Object, writer *dynmap.Object) {
func (this *DashTemplateEvaluator) EvalObject(source *simplejson.Json, writer *simplejson.Json) {
for key, value := range source.Map() {
for key, value := range source.MustMap() {
if key == "__inputs" {
continue
}
goValue := value.Interface()
switch v := goValue.(type) {
switch v := value.(type) {
case string:
interpolated := this.varRegex.ReplaceAllStringFunc(v, func(match string) string {
return this.variables[match]
})
writer.SetValue(key, interpolated)
writer.Set(key, interpolated)
case map[string]interface{}:
childSource, _ := value.Object()
childWriter, _ := writer.SetValue(key, map[string]interface{}{}).Object()
childSource := simplejson.NewFromAny(value)
childWriter := simplejson.New()
writer.Set(key, childWriter.Interface())
this.EvalObject(childSource, childWriter)
case []interface{}:
default:
log.Info("type: %v", reflect.TypeOf(goValue))
log.Error(3, "Unknown json type key: %v , type: %v", key, goValue)
log.Info("type: %v", reflect.TypeOf(value))
log.Error(3, "Unknown json type key: %v , type: %v", key, value)
}
}
}

View File

@ -4,7 +4,7 @@ import (
"testing"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/dynmap"
"github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
@ -44,21 +44,16 @@ func TestDashboardImport(t *testing.T) {
Convey("should install dashboard", func() {
So(importedDash, ShouldNotBeNil)
dashData := dynmap.NewFromMap(importedDash.Data)
So(dashData.String(), ShouldEqual, "")
dashStr, _ := importedDash.Data.EncodePretty()
So(string(dashStr), ShouldEqual, "")
rows := importedDash.Data["rows"].([]interface{})
row1 := rows[0].(map[string]interface{})
panels := row1["panels"].([]interface{})
panel := panels[0].(map[string]interface{})
So(panel["datasource"], ShouldEqual, "graphite")
So(importedDash.Data["__inputs"], ShouldBeNil)
// So(panel["datasource"], ShouldEqual, "graphite")
// So(importedDash.Data["__inputs"], ShouldBeNil)
})
})
Convey("When evaling dashboard template", t, func() {
template, _ := dynmap.NewObjectFromBytes([]byte(`{
template, _ := simplejson.NewJson([]byte(`{
"__inputs": {
"graphite": {
"type": "datasource"
@ -80,12 +75,12 @@ func TestDashboardImport(t *testing.T) {
So(err, ShouldBeNil)
Convey("should render template", func() {
So(res.MustGetString("test.prop", ""), ShouldEqual, "my-server")
So(res.GetPath("test", "prop").MustString(), ShouldEqual, "my-server")
})
Convey("should not include inputs in output", func() {
_, err := res.GetObject("__inputs")
So(err, ShouldNotBeNil)
inputs := res.Get("__inputs")
So(inputs.Interface(), ShouldBeNil)
})
})

View File

@ -1,11 +1,11 @@
package plugins
import (
"encoding/json"
"os"
"path/filepath"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models"
)
@ -52,10 +52,8 @@ func loadPluginDashboard(plugin *PluginBase, path string) (*m.Dashboard, error)
defer reader.Close()
jsonParser := json.NewDecoder(reader)
var data map[string]interface{}
if err := jsonParser.Decode(&data); err != nil {
data, err := simplejson.NewFromReader(reader)
if err != nil {
return nil, err
}

View File

@ -23,7 +23,7 @@ func TestPluginDashboards(t *testing.T) {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
if query.Slug == "nginx-connections" {
dash := m.NewDashboard("Nginx Connections")
dash.Data["revision"] = "1.1"
dash.Data.Set("revision", "1.1")
query.Result = dash
return nil
}