Skip to content

Commit

Permalink
Refactor paginated bounce query function to return DB total.
Browse files Browse the repository at this point in the history
  • Loading branch information
knadh committed May 3, 2022
1 parent d2ef23d commit 5fd4d7b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
6 changes: 3 additions & 3 deletions cmd/bounce.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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

Expand All @@ -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
}
Expand Down
14 changes: 10 additions & 4 deletions internal/core/bounces.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand All @@ -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.
Expand Down

0 comments on commit 5fd4d7b

Please # to comment.