Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Refactor paginated campaign query function to return DB total.

Kailash Nadhd2ef23d3faa1
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index a35b8375..d725969f 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -60,7 +60,7 @@ func handleGetCampaigns(c echo.Context) error {
noBody, _ = strconv.ParseBool(c.QueryParam("no_body"))
)
- res, err := app.core.QueryCampaigns(query, status, orderBy, order, pg.Offset, pg.Limit)
+ res, total, err := app.core.QueryCampaigns(query, status, orderBy, order, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -78,8 +78,9 @@ func handleGetCampaigns(c echo.Context) error {
}
// Meta.
+ out.Query = query
out.Results = res
- out.Total = res[0].Total
+ out.Total = total
out.Page = pg.Page
out.PerPage = pg.PerPage
diff --git a/internal/core/campaigns.go b/internal/core/campaigns.go
index 5590f619..6d8e68cf 100644
--- a/internal/core/campaigns.go
+++ b/internal/core/campaigns.go
@@ -17,9 +17,9 @@ const (
CampaignAnalyticsBounces = "bounces"
)
-// QueryCampaigns retrieves campaigns optionally filtering them by
-// the given arbitrary query expression.
-func (c *Core) QueryCampaigns(searchStr string, statuses []string, orderBy, order string, offset, limit int) (models.Campaigns, error) {
+// QueryCampaigns retrieves paginated campaigns optionally filtering them by the given arbitrary
+// query expression. It also returns the total number of records in the DB.
+func (c *Core) QueryCampaigns(searchStr string, statuses []string, orderBy, order string, offset, limit int) (models.Campaigns, int, error) {
queryStr, stmt := makeSearchQuery(searchStr, orderBy, order, c.q.QueryCampaigns)
if statuses == nil {
@@ -30,7 +30,7 @@ func (c *Core) QueryCampaigns(searchStr string, statuses []string, orderBy, orde
var out models.Campaigns
if err := c.db.Select(&out, stmt, 0, pq.Array(statuses), queryStr, offset, limit); err != nil {
c.log.Printf("error fetching campaigns: %v", err)
- return nil, echo.NewHTTPError(http.StatusInternalServerError,
+ return nil, 0, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.campaign}", "error", pqErrMsg(err)))
}
@@ -44,11 +44,16 @@ func (c *Core) QueryCampaigns(searchStr string, statuses []string, orderBy, orde
// Lazy load stats.
if err := out.LoadStats(c.q.GetCampaignStats); err != nil {
c.log.Printf("error fetching campaign stats: %v", err)
- return nil, echo.NewHTTPError(http.StatusInternalServerError,
+ return nil, 0, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.campaigns}", "error", pqErrMsg(err)))
}
- return out, nil
+ total := 0
+ if len(out) > 0 {
+ total = out[0].Total
+ }
+
+ return out, total, nil
}
// GetCampaign retrieves a campaign.