From 5fd4d7b44b5811e5a3074a592d044677989a0479 Mon Sep 17 00:00:00 2001 From: Kailash Nadh Date: Sun, 1 May 2022 15:19:40 +0530 Subject: [PATCH] Refactor paginated bounce query function to return DB total. --- cmd/bounce.go | 6 +++--- internal/core/bounces.go | 14 ++++++++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/cmd/bounce.go b/cmd/bounce.go index a38001b4f..f9e370ae0 100644 --- a/cmd/bounce.go +++ b/cmd/bounce.go @@ -33,7 +33,7 @@ func handleGetBounces(c echo.Context) error { return c.JSON(http.StatusOK, okResp{out}) } - res, err := app.core.QueryBounces(campID, 0, source, orderBy, order, pg.Offset, pg.Limit) + res, total, err := app.core.QueryBounces(campID, 0, source, orderBy, order, pg.Offset, pg.Limit) if err != nil { return err } @@ -47,7 +47,7 @@ func handleGetBounces(c echo.Context) error { // Meta. out.Results = res - out.Total = res[0].Total + out.Total = total out.Page = pg.Page out.PerPage = pg.PerPage @@ -65,7 +65,7 @@ func handleGetSubscriberBounces(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID")) } - out, err := app.core.QueryBounces(0, subID, "", "", "", 0, 1000) + out, _, err := app.core.QueryBounces(0, subID, "", "", "", 0, 1000) if err != nil { return err } diff --git a/internal/core/bounces.go b/internal/core/bounces.go index 70cad8b76..0d4e66395 100644 --- a/internal/core/bounces.go +++ b/internal/core/bounces.go @@ -11,8 +11,9 @@ import ( var bounceQuerySortFields = []string{"email", "campaign_name", "source", "created_at"} -// QueryBounces retrieves bounce entries based on the given params. -func (c *Core) QueryBounces(campID, subID int, source, orderBy, order string, offset, limit int) ([]models.Bounce, error) { +// QueryBounces retrieves paginated bounce entries based on the given params. +// It also returns the total number of bounce records in the DB. +func (c *Core) QueryBounces(campID, subID int, source, orderBy, order string, offset, limit int) ([]models.Bounce, int, error) { if !strSliceContains(orderBy, bounceQuerySortFields) { orderBy = "created_at" } @@ -24,11 +25,16 @@ func (c *Core) QueryBounces(campID, subID int, source, orderBy, order string, of stmt := fmt.Sprintf(c.q.QueryBounces, orderBy, order) if err := c.db.Select(&out, stmt, 0, campID, subID, source, offset, limit); err != nil { c.log.Printf("error fetching bounces: %v", err) - return nil, echo.NewHTTPError(http.StatusInternalServerError, + return nil, 0, echo.NewHTTPError(http.StatusInternalServerError, c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.bounce}", "error", pqErrMsg(err))) } - return out, nil + total := 0 + if len(out) > 0 { + total = out[0].Total + } + + return out, total, nil } // GetBounce retrieves bounce entries based on the given params.