1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-01-08 09:14:37 +02:00
pocketbase/apis/logs.go

82 lines
1.8 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package apis
import (
"net/http"
"github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
2022-07-06 23:19:05 +02:00
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/search"
)
2022-10-30 10:28:14 +02:00
// bindLogsApi registers the request logs api endpoints.
func bindLogsApi(app core.App, rg *echo.Group) {
2022-07-06 23:19:05 +02:00
api := logsApi{app: app}
subGroup := rg.Group("/logs", RequireAdminAuth())
2023-11-26 13:33:17 +02:00
subGroup.GET("", api.list)
subGroup.GET("/stats", api.stats)
subGroup.GET("/:id", api.view)
2022-07-06 23:19:05 +02:00
}
type logsApi struct {
app core.App
}
2023-11-26 13:33:17 +02:00
var logFilterFields = []string{
2022-07-06 23:19:05 +02:00
"rowid", "id", "created", "updated",
2023-11-26 13:33:17 +02:00
"level", "message", "data",
`^data\.[\w\.\:]*\w+$`,
2022-07-06 23:19:05 +02:00
}
2023-11-26 13:33:17 +02:00
func (api *logsApi) list(c echo.Context) error {
fieldResolver := search.NewSimpleFieldResolver(logFilterFields...)
2022-07-06 23:19:05 +02:00
result, err := search.NewProvider(fieldResolver).
2023-11-26 13:33:17 +02:00
Query(api.app.LogsDao().LogQuery()).
ParseAndExec(c.QueryParams().Encode(), &[]*models.Log{})
2022-07-06 23:19:05 +02:00
if err != nil {
2022-10-30 10:28:14 +02:00
return NewBadRequestError("", err)
2022-07-06 23:19:05 +02:00
}
return c.JSON(http.StatusOK, result)
}
2023-11-26 13:33:17 +02:00
func (api *logsApi) stats(c echo.Context) error {
fieldResolver := search.NewSimpleFieldResolver(logFilterFields...)
2022-07-06 23:19:05 +02:00
filter := c.QueryParam(search.FilterQueryParam)
var expr dbx.Expression
if filter != "" {
var err error
expr, err = search.FilterData(filter).BuildExpr(fieldResolver)
if err != nil {
2022-10-30 10:28:14 +02:00
return NewBadRequestError("Invalid filter format.", err)
2022-07-06 23:19:05 +02:00
}
}
2023-11-26 13:33:17 +02:00
stats, err := api.app.LogsDao().LogsStats(expr)
2022-07-06 23:19:05 +02:00
if err != nil {
2023-11-26 13:33:17 +02:00
return NewBadRequestError("Failed to generate logs stats.", err)
2022-07-06 23:19:05 +02:00
}
return c.JSON(http.StatusOK, stats)
}
2023-11-26 13:33:17 +02:00
func (api *logsApi) view(c echo.Context) error {
2022-07-06 23:19:05 +02:00
id := c.PathParam("id")
if id == "" {
2022-10-30 10:28:14 +02:00
return NewNotFoundError("", nil)
2022-07-06 23:19:05 +02:00
}
2023-11-26 13:33:17 +02:00
log, err := api.app.LogsDao().FindLogById(id)
if err != nil || log == nil {
2022-10-30 10:28:14 +02:00
return NewNotFoundError("", err)
2022-07-06 23:19:05 +02:00
}
2023-11-26 13:33:17 +02:00
return c.JSON(http.StatusOK, log)
2022-07-06 23:19:05 +02:00
}