From 36094a6717aba53ec6241a0d9f87555295122105 Mon Sep 17 00:00:00 2001 From: valentinkolb Date: Wed, 13 Nov 2024 00:35:28 +0100 Subject: [PATCH] feat(analyticsApi): added page and perPage as well as sort to /api/analytics/pageViewCount endpoint --- analyticsApi/main.go | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/analyticsApi/main.go b/analyticsApi/main.go index ac6e499..1e62999 100644 --- a/analyticsApi/main.go +++ b/analyticsApi/main.go @@ -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= +// ?perPage= +// ?sort= (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)