Ver código fonte

dashboards: extract short uid generator to util package. #7883

Marcus Efraimsson 8 anos atrás
pai
commit
e229f8aea8
2 arquivos alterados com 27 adições e 9 exclusões
  1. 3 9
      pkg/models/dashboards.go
  2. 24 0
      pkg/util/shortid_generator.go

+ 3 - 9
pkg/models/dashboards.go

@@ -7,7 +7,7 @@ import (
 
 	"github.com/gosimple/slug"
 	"github.com/grafana/grafana/pkg/components/simplejson"
-	"github.com/teris-io/shortid"
+	"github.com/grafana/grafana/pkg/util"
 )
 
 // Typed errors
@@ -63,7 +63,7 @@ type Dashboard struct {
 // NewDashboard creates a new dashboard
 func NewDashboard(title string) *Dashboard {
 	dash := &Dashboard{}
-	dash.Uid = DashboardUid()
+	dash.Uid, _ = util.GenerateShortUid()
 	dash.Data = simplejson.New()
 	dash.Data.Set("title", title)
 	dash.Title = title
@@ -113,18 +113,12 @@ func NewDashboardFromJson(data *simplejson.Json) *Dashboard {
 	if uid, err := dash.Data.Get("uid").String(); err == nil {
 		dash.Uid = uid
 	} else {
-		dash.Uid = DashboardUid()
+		dash.Uid, _ = util.GenerateShortUid()
 	}
 
 	return dash
 }
 
-func DashboardUid() string {
-	gen, _ := shortid.New(1, shortid.DefaultABC, 1)
-	uid, _ := gen.Generate()
-	return uid
-}
-
 // GetDashboardModel turns the command into the savable model
 func (cmd *SaveDashboardCommand) GetDashboardModel() *Dashboard {
 	dash := NewDashboardFromJson(cmd.Dashboard)

+ 24 - 0
pkg/util/shortid_generator.go

@@ -0,0 +1,24 @@
+package util
+
+import (
+	"github.com/teris-io/shortid"
+)
+
+func init() {
+	gen, _ := shortid.New(1, shortid.DefaultABC, 1)
+	shortid.SetDefault(gen)
+
+}
+
+// GenerateShortUid generates a short unique identifier.
+func GenerateShortUid() (uid string, err error) {
+	if uid, err = shortid.Generate(); err != nil {
+		if uid, err = shortid.Generate(); err != nil {
+			if uid, err = shortid.Generate(); err != nil {
+				return "", err
+			}
+		}
+	}
+
+	return uid, nil
+}