swirl/api/dashboard.go

93 lines
2.2 KiB
Go
Raw Permalink Normal View History

package api
import (
"strings"
"github.com/cuigh/auxo/data"
"github.com/cuigh/auxo/errors"
"github.com/cuigh/auxo/ext/times"
"github.com/cuigh/auxo/net/web"
"github.com/cuigh/swirl/biz"
2021-12-23 11:28:31 +00:00
"github.com/cuigh/swirl/dao"
2022-01-06 08:54:14 +00:00
"github.com/cuigh/swirl/misc"
)
// DashboardHandler encapsulates dashboard related handlers.
type DashboardHandler struct {
Find web.HandlerFunc `path:"/find" auth:"?" desc:"find dashboard by name and key"`
Save web.HandlerFunc `path:"/save" method:"post" auth:"dashboard.edit" desc:"save dashboard"`
FetchData web.HandlerFunc `path:"/fetch-data" auth:"?" desc:"fetch data of dashboard charts"`
}
// NewDashboard creates an instance of DashboardHandler
func NewDashboard(b biz.DashboardBiz) *DashboardHandler {
return &DashboardHandler{
Find: dashboardFind(b),
Save: dashboardSave(b),
FetchData: dashboardFetchData(b),
}
}
func dashboardFind(b biz.DashboardBiz) web.HandlerFunc {
2022-01-06 08:54:14 +00:00
return func(c web.Context) (err error) {
var (
2021-12-23 11:28:31 +00:00
d *dao.Dashboard
2022-01-06 08:54:14 +00:00
name = c.Query("name")
key = c.Query("key")
)
2022-01-06 08:54:14 +00:00
ctx, cancel := misc.Context(defaultTimeout)
defer cancel()
d, err = b.FindDashboard(ctx, name, key)
if err != nil {
return err
}
2022-01-06 08:54:14 +00:00
return success(c, d)
}
}
func dashboardSave(b biz.DashboardBiz) web.HandlerFunc {
2022-01-06 08:54:14 +00:00
return func(c web.Context) error {
2021-12-23 11:28:31 +00:00
dashboard := &dao.Dashboard{}
2022-01-06 08:54:14 +00:00
err := c.Bind(dashboard)
if err != nil {
return err
}
switch dashboard.Name {
case "home", "service":
2022-01-06 08:54:14 +00:00
ctx, cancel := misc.Context(defaultTimeout)
defer cancel()
err = b.UpdateDashboard(ctx, dashboard, c.User())
default:
err = errors.New("unknown dashboard: " + dashboard.Name)
}
2022-01-06 08:54:14 +00:00
return ajax(c, err)
}
}
func dashboardFetchData(b biz.DashboardBiz) web.HandlerFunc {
type Args struct {
Key string `json:"key" bind:"key"`
Dashboards string `json:"charts" bind:"charts"`
Period int32 `json:"period" bind:"period"`
}
2022-01-06 08:54:14 +00:00
return func(c web.Context) (err error) {
var (
args = &Args{}
d data.Map
)
2022-01-06 08:54:14 +00:00
if err = c.Bind(args); err == nil {
ctx, cancel := misc.Context(defaultTimeout)
defer cancel()
d, err = b.FetchData(ctx, args.Key, strings.Split(args.Dashboards, ","), times.Minutes(args.Period))
}
if err != nil {
return err
}
2022-01-06 08:54:14 +00:00
return success(c, d)
}
}