Refactor paginated bounce query function to return DB total.

This commit is contained in:
Kailash Nadh 2022-05-01 15:19:40 +05:30
parent d2ef23d3fa
commit 5fd4d7b44b
2 changed files with 13 additions and 7 deletions

View file

@ -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
}

View file

@ -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.