Refactor paginated list query function to return DB total.

This commit is contained in:
Kailash Nadh 2022-05-01 15:12:31 +05:30
parent aa19771307
commit e303850584
2 changed files with 37 additions and 26 deletions

View file

@ -49,7 +49,7 @@ func handleGetLists(c echo.Context) error {
}
// Full list query.
res, err := app.core.QueryLists(query, orderBy, order, pg.Offset, pg.Limit)
res, total, err := app.core.QueryLists(query, orderBy, order, pg.Offset, pg.Limit)
if err != nil {
return err
}
@ -59,33 +59,15 @@ func handleGetLists(c echo.Context) error {
app.i18n.Ts("globals.messages.notFound", "name", "{globals.terms.list}"))
}
// Replace null tags.
for i, v := range res {
if v.Tags == nil {
res[i].Tags = make([]string, 0)
}
// Total counts.
for _, c := range v.SubscriberCounts {
res[i].SubscriberCount += c
}
}
if single {
return c.JSON(http.StatusOK, okResp{res[0]})
}
// Meta.
// TODO: add .query?
out.Query = query
out.Results = res
if len(res) > 0 {
out.Total = res[0].Total
}
out.Total = total
out.Page = pg.Page
out.PerPage = pg.PerPage
if out.PerPage == 0 {
out.PerPage = out.Total
}
return c.JSON(http.StatusOK, okResp{out})
}

View file

@ -13,29 +13,58 @@ import (
func (c *Core) GetLists(typ string) ([]models.List, error) {
out := []models.List{}
// TODO: remove orderBy
if err := c.q.GetLists.Select(&out, typ, "id"); err != nil {
c.log.Printf("error fetching lists: %v", err)
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.lists}", "error", pqErrMsg(err)))
}
// Replace null tags.
for i, l := range out {
if l.Tags == nil {
out[i].Tags = []string{}
}
// Total counts.
for _, c := range l.SubscriberCounts {
out[i].SubscriberCount += c
}
}
return out, nil
}
// QueryLists gets multiple lists based on multiple query params.
func (c *Core) QueryLists(searchStr, orderBy, order string, offset, limit int) ([]models.List, error) {
// QueryLists gets multiple lists based on multiple query params. Along with the paginated and sliced
// results, the total number of lists in the DB is returned.
func (c *Core) QueryLists(searchStr, orderBy, order string, offset, limit int) ([]models.List, int, error) {
out := []models.List{}
queryStr, stmt := makeSearchQuery(searchStr, orderBy, order, c.q.QueryLists)
if err := c.db.Select(&out, stmt, 0, "", queryStr, offset, limit); err != nil {
c.log.Printf("error fetching lists: %v", err)
return nil, echo.NewHTTPError(http.StatusInternalServerError,
return nil, 0, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.lists}", "error", pqErrMsg(err)))
}
return out, nil
total := 0
if len(out) > 0 {
total = out[0].Total
// Replace null tags.
for i, l := range out {
if l.Tags == nil {
out[i].Tags = []string{}
}
// Total counts.
for _, c := range l.SubscriberCounts {
out[i].SubscriberCount += c
}
}
}
return out, total, nil
}
// GetList gets a list by its ID or UUID.