Chore: Moves common and response into separate packages (#30298)

* Chore: moves common and response into separate packages

* Chore: moves common and response into separate packages

* Update pkg/api/utils/common.go

Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>

* Chore: changes after PR comments

* Chore: move wrap to routing package

* Chore: move functions in common to response package

* Chore: move functions in common to response package

* Chore: formats imports

Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Hugo Häggmark
2021-01-15 14:43:20 +01:00
committed by GitHub
co-authored by Arve Knudsen
parent a94c256516
commit 3d41267fc4
51 changed files with 1321 additions and 1248 deletions
+52 -51
View File
@@ -12,6 +12,7 @@ import (
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/dashdiffs"
"github.com/grafana/grafana/pkg/components/simplejson"
@@ -38,15 +39,15 @@ func isDashboardStarredByUser(c *models.ReqContext, dashID int64) (bool, error)
return query.Result, nil
}
func dashboardGuardianResponse(err error) Response {
func dashboardGuardianResponse(err error) response.Response {
if err != nil {
return Error(500, "Error while checking dashboard permissions", err)
return response.Error(500, "Error while checking dashboard permissions", err)
}
return Error(403, "Access denied to this dashboard", nil)
return response.Error(403, "Access denied to this dashboard", nil)
}
func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
slug := c.Params(":slug")
uid := c.Params(":uid")
dash, rsp := getDashboardHelper(c.OrgId, slug, 0, uid)
@@ -64,7 +65,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
}
}
if isEmptyData {
return Error(500, "Error while loading dashboard, dashboard data is invalid", nil)
return response.Error(500, "Error while loading dashboard, dashboard data is invalid", nil)
}
}
@@ -79,7 +80,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
isStarred, err := isDashboardStarredByUser(c, dash.Id)
if err != nil {
return Error(500, "Error while checking if dashboard was starred by user", err)
return response.Error(500, "Error while checking if dashboard was starred by user", err)
}
// Finding creator and last updater of the dashboard
@@ -115,7 +116,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
if dash.FolderId > 0 {
query := models.GetDashboardQuery{Id: dash.FolderId, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
return Error(500, "Dashboard folder could not be read", err)
return response.Error(500, "Dashboard folder could not be read", err)
}
meta.FolderTitle = query.Result.Title
meta.FolderUrl = query.Result.GetUrl()
@@ -123,7 +124,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
provisioningData, err := dashboards.NewProvisioningService().GetProvisionedDashboardDataByDashboardID(dash.Id)
if err != nil {
return Error(500, "Error while checking if dashboard is provisioned", err)
return response.Error(500, "Error while checking if dashboard is provisioned", err)
}
if provisioningData != nil {
@@ -152,7 +153,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response {
}
c.TimeRequest(metrics.MApiDashboardGet)
return JSON(200, dto)
return response.JSON(200, dto)
}
func getUserLogin(userID int64) string {
@@ -164,7 +165,7 @@ func getUserLogin(userID int64) string {
return query.Result.Login
}
func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*models.Dashboard, Response) {
func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*models.Dashboard, response.Response) {
var query models.GetDashboardQuery
if len(uid) > 0 {
@@ -174,31 +175,31 @@ func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*models
}
if err := bus.Dispatch(&query); err != nil {
return nil, Error(404, "Dashboard not found", err)
return nil, response.Error(404, "Dashboard not found", err)
}
return query.Result, nil
}
func DeleteDashboardBySlug(c *models.ReqContext) Response {
func DeleteDashboardBySlug(c *models.ReqContext) response.Response {
query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")}
if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to retrieve dashboards by slug", err)
return response.Error(500, "Failed to retrieve dashboards by slug", err)
}
if len(query.Result) > 1 {
return JSON(412, util.DynMap{"status": "multiple-slugs-exists", "message": models.ErrDashboardsWithSameSlugExists.Error()})
return response.JSON(412, util.DynMap{"status": "multiple-slugs-exists", "message": models.ErrDashboardsWithSameSlugExists.Error()})
}
return deleteDashboard(c)
}
func DeleteDashboardByUID(c *models.ReqContext) Response {
func DeleteDashboardByUID(c *models.ReqContext) response.Response {
return deleteDashboard(c)
}
func deleteDashboard(c *models.ReqContext) Response {
func deleteDashboard(c *models.ReqContext) response.Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid"))
if rsp != nil {
return rsp
@@ -214,21 +215,21 @@ func deleteDashboard(c *models.ReqContext) Response {
var dashboardErr models.DashboardErr
if ok := errors.As(err, &dashboardErr); ok {
if errors.Is(err, models.ErrDashboardCannotDeleteProvisionedDashboard) {
return Error(dashboardErr.StatusCode, dashboardErr.Error(), err)
return response.Error(dashboardErr.StatusCode, dashboardErr.Error(), err)
}
}
return Error(500, "Failed to delete dashboard", err)
return response.Error(500, "Failed to delete dashboard", err)
}
return JSON(200, util.DynMap{
return response.JSON(200, util.DynMap{
"title": dash.Title,
"message": fmt.Sprintf("Dashboard %s deleted", dash.Title),
"id": dash.Id,
})
}
func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboardCommand) Response {
func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboardCommand) response.Response {
cmd.OrgId = c.OrgId
cmd.UserId = c.UserId
@@ -238,16 +239,16 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboa
if newDashboard {
limitReached, err := hs.QuotaService.QuotaReached(c, "dashboard")
if err != nil {
return Error(500, "failed to get quota", err)
return response.Error(500, "failed to get quota", err)
}
if limitReached {
return Error(403, "Quota reached", nil)
return response.Error(403, "Quota reached", nil)
}
}
provisioningData, err := dashboards.NewProvisioningService().GetProvisionedDashboardDataByDashboardID(dash.Id)
if err != nil {
return Error(500, "Error while checking if dashboard is provisioned", err)
return response.Error(500, "Error while checking if dashboard is provisioned", err)
}
allowUiUpdate := true
@@ -288,7 +289,7 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboa
}
c.TimeRequest(metrics.MApiDashboardSave)
return JSON(200, util.DynMap{
return response.JSON(200, util.DynMap{
"status": "success",
"slug": dashboard.Slug,
"version": dashboard.Version,
@@ -298,25 +299,25 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboa
})
}
func dashboardSaveErrorToApiResponse(err error) Response {
func dashboardSaveErrorToApiResponse(err error) response.Response {
var dashboardErr models.DashboardErr
if ok := errors.As(err, &dashboardErr); ok {
if body := dashboardErr.Body(); body != nil {
return JSON(dashboardErr.StatusCode, body)
return response.JSON(dashboardErr.StatusCode, body)
}
if errors.Is(dashboardErr, models.ErrDashboardUpdateAccessDenied) {
return Error(dashboardErr.StatusCode, dashboardErr.Error(), err)
return response.Error(dashboardErr.StatusCode, dashboardErr.Error(), err)
}
return Error(dashboardErr.StatusCode, dashboardErr.Error(), nil)
return response.Error(dashboardErr.StatusCode, dashboardErr.Error(), nil)
}
if errors.Is(err, models.ErrFolderNotFound) {
return Error(400, err.Error(), nil)
return response.Error(400, err.Error(), nil)
}
var validationErr alerting.ValidationError
if ok := errors.As(err, &validationErr); ok {
return Error(422, validationErr.Error(), nil)
return response.Error(422, validationErr.Error(), nil)
}
var pluginErr models.UpdatePluginDashboardError
@@ -326,17 +327,17 @@ func dashboardSaveErrorToApiResponse(err error) Response {
if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist {
message = fmt.Sprintf("The dashboard belongs to plugin %s.", pluginDef.Name)
}
return JSON(412, util.DynMap{"status": "plugin-dashboard", "message": message})
return response.JSON(412, util.DynMap{"status": "plugin-dashboard", "message": message})
}
return Error(500, "Failed to save dashboard", err)
return response.Error(500, "Failed to save dashboard", err)
}
// GetHomeDashboard returns the home dashboard.
func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) Response {
func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) response.Response {
prefsQuery := models.GetPreferencesWithDefaultsQuery{User: c.SignedInUser}
if err := hs.Bus.Dispatch(&prefsQuery); err != nil {
return Error(500, "Failed to get preferences", err)
return response.Error(500, "Failed to get preferences", err)
}
if prefsQuery.Result.HomeDashboardId != 0 {
@@ -345,7 +346,7 @@ func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) Response {
if err == nil {
url := models.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug)
dashRedirect := dtos.DashboardRedirect{RedirectUri: url}
return JSON(200, &dashRedirect)
return response.JSON(200, &dashRedirect)
}
hs.log.Warn("Failed to get slug from database", "err", err)
}
@@ -360,7 +361,7 @@ func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) Response {
// nolint:gosec
file, err := os.Open(filePath)
if err != nil {
return Error(500, "Failed to load home dashboard", err)
return response.Error(500, "Failed to load home dashboard", err)
}
defer func() {
if err := file.Close(); err != nil {
@@ -375,12 +376,12 @@ func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) Response {
jsonParser := json.NewDecoder(file)
if err := jsonParser.Decode(&dash.Dashboard); err != nil {
return Error(500, "Failed to load home dashboard", err)
return response.Error(500, "Failed to load home dashboard", err)
}
hs.addGettingStartedPanelToHomeDashboard(c, dash.Dashboard)
return JSON(200, &dash)
return response.JSON(200, &dash)
}
func (hs *HTTPServer) addGettingStartedPanelToHomeDashboard(c *models.ReqContext, dash *simplejson.Json) {
@@ -410,7 +411,7 @@ func (hs *HTTPServer) addGettingStartedPanelToHomeDashboard(c *models.ReqContext
}
// GetDashboardVersions returns all dashboard versions as JSON
func GetDashboardVersions(c *models.ReqContext) Response {
func GetDashboardVersions(c *models.ReqContext) response.Response {
dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
@@ -426,7 +427,7 @@ func GetDashboardVersions(c *models.ReqContext) Response {
}
if err := bus.Dispatch(&query); err != nil {
return Error(404, fmt.Sprintf("No versions found for dashboardId %d", dashID), err)
return response.Error(404, fmt.Sprintf("No versions found for dashboardId %d", dashID), err)
}
for _, version := range query.Result {
@@ -445,11 +446,11 @@ func GetDashboardVersions(c *models.ReqContext) Response {
}
}
return JSON(200, query.Result)
return response.JSON(200, query.Result)
}
// GetDashboardVersion returns the dashboard version with the given ID.
func GetDashboardVersion(c *models.ReqContext) Response {
func GetDashboardVersion(c *models.ReqContext) response.Response {
dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
@@ -464,7 +465,7 @@ func GetDashboardVersion(c *models.ReqContext) Response {
}
if err := bus.Dispatch(&query); err != nil {
return Error(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err)
return response.Error(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err)
}
creator := anonString
@@ -484,11 +485,11 @@ func GetDashboardVersion(c *models.ReqContext) Response {
CreatedBy: creator,
}
return JSON(200, dashVersionMeta)
return response.JSON(200, dashVersionMeta)
}
// POST /api/dashboards/calculate-diff performs diffs on two dashboards
func CalculateDashboardDiff(c *models.ReqContext, apiOptions dtos.CalculateDiffOptions) Response {
func CalculateDashboardDiff(c *models.ReqContext, apiOptions dtos.CalculateDiffOptions) response.Response {
guardianBase := guardian.New(apiOptions.Base.DashboardId, c.OrgId, c.SignedInUser)
if canSave, err := guardianBase.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
@@ -519,20 +520,20 @@ func CalculateDashboardDiff(c *models.ReqContext, apiOptions dtos.CalculateDiffO
result, err := dashdiffs.CalculateDiff(&options)
if err != nil {
if errors.Is(err, models.ErrDashboardVersionNotFound) {
return Error(404, "Dashboard version not found", err)
return response.Error(404, "Dashboard version not found", err)
}
return Error(500, "Unable to compute diff", err)
return response.Error(500, "Unable to compute diff", err)
}
if options.DiffType == dashdiffs.DiffDelta {
return Respond(200, result.Delta).Header("Content-Type", "application/json")
return response.Respond(200, result.Delta).Header("Content-Type", "application/json")
}
return Respond(200, result.Delta).Header("Content-Type", "text/html")
return response.Respond(200, result.Delta).Header("Content-Type", "text/html")
}
// RestoreDashboardVersion restores a dashboard to the given version.
func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext, apiCmd dtos.RestoreDashboardVersionCommand) Response {
func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext, apiCmd dtos.RestoreDashboardVersionCommand) response.Response {
dash, rsp := getDashboardHelper(c.OrgId, "", c.ParamsInt64(":dashboardId"), "")
if rsp != nil {
return rsp
@@ -545,7 +546,7 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext, apiCmd dtos.
versionQuery := models.GetDashboardVersionQuery{DashboardId: dash.Id, Version: apiCmd.Version, OrgId: c.OrgId}
if err := bus.Dispatch(&versionQuery); err != nil {
return Error(404, "Dashboard version not found", nil)
return response.Error(404, "Dashboard version not found", nil)
}
version := versionQuery.Result