feat(analyticsApi): added page and perPage as well as sort to /api/analytics/pageViewCount endpoint
Build and Push Docker image / build-and-push (push) Successful in 3m41s Details

This commit is contained in:
Valentin Kolb 2024-11-13 00:35:28 +01:00
parent 92b03054d9
commit 36094a6717
1 changed files with 32 additions and 3 deletions

View File

@ -8,6 +8,7 @@ import (
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"strconv"
"time"
)
@ -17,13 +18,19 @@ import (
// It adds the following endpoint to the app:
// GET /api/analytics/pageViewCount
//
// The endpoint expects the following query parameter:
// The endpoint expects the following query parameters:
//
// ?startDate=ISO 8601 formatted date (optional)
// ?page=<page number>
// ?perPage=<results per page>
// ?sort=<ASC|DESC> (default is ASC)
//
// - `startDate`: An optional start date in ISO 8601 format (e.g., "2024-11-12T15:04:05Z").
// If provided, the global count reflects views from this date onward.
// If not provided, the global count includes all views.
// - `page`: Page number for pagination (default is 1).
// - `perPage`: Number of results per page for pagination (default is 10).
// - `sort`: Sorting order, either `ASC` or `DESC` for ascending or descending order.
//
// Response format:
// [
@ -59,13 +66,30 @@ func initPageViewCount(app *pocketbase.PocketBase, e *core.ServeEvent) {
var startDate time.Time
var err error
if startDateParam != "" {
// Parse the startDate, expecting an ISO 8601 format
startDate, err = time.Parse(time.RFC3339, startDateParam)
if err != nil {
return apis.NewBadRequestError("Invalid start date format, expected ISO 8601", err)
}
}
// Get pagination and sorting parameters
page, _ := strconv.Atoi(c.QueryParam("page"))
if page < 1 {
page = 1
}
perPage, _ := strconv.Atoi(c.QueryParam("perPage"))
if perPage < 1 {
perPage = 10
}
sort := c.QueryParam("sort")
if sort != "DESC" {
sort = "ASC" // default sorting order
}
offset := (page - 1) * perPage
type PageViewData struct {
ID int `json:"id"`
Data string `json:"data"`
@ -75,7 +99,7 @@ func initPageViewCount(app *pocketbase.PocketBase, e *core.ServeEvent) {
var result []PageViewData
// Execute the query with nested JSON aggregation
// Execute the query with nested JSON aggregation, pagination, and sorting
err = app.Dao().DB().
NewQuery(`
SELECT
@ -108,9 +132,14 @@ func initPageViewCount(app *pocketbase.PocketBase, e *core.ServeEvent) {
analyticsPageViews view
GROUP BY
view.path
ORDER BY
data ` + sort + `
LIMIT {:perPage} OFFSET {:offset}
`).
Bind(dbx.Params{
"startDate": startDate,
"perPage": perPage,
"offset": offset,
}).
All(&result)