Add sort order for prober data table

Allowed sort order by `id` and `last_submit_ts`
This commit is contained in:
ditatompel 2024-05-04 01:11:21 +07:00
parent dbc07e66a8
commit 949db1573b
No known key found for this signature in database
GPG key ID: 31D3D06D77950979
3 changed files with 26 additions and 10 deletions

View file

@ -12,7 +12,7 @@ const getParams = ({ pageNumber, rowsPerPage, sort, filters }) => {
let params = `page=${pageNumber}&limit=${rowsPerPage}`;
if (sort) {
params += `&orderBy=${sort.orderBy}&orderDir=${sort.direction}`;
params += `&sort_by=${sort.orderBy}&sort_direction=${sort.direction}`;
}
if (filters) {
params += filters.map(({ filterBy, value }) => `&${filterBy}=${value}`).join('');

View file

@ -90,10 +90,12 @@ func Prober(c *fiber.Ctx) error {
}
query := repo.ProbersQueryParams{
RowsPerPage: c.QueryInt("limit", 10),
Page: c.QueryInt("page", 1),
Name: c.Query("name"),
ApiKey: c.Query("api_key"),
RowsPerPage: c.QueryInt("limit", 10),
Page: c.QueryInt("page", 1),
SortBy: c.Query("sort_by", "id"),
SortDirection: c.Query("sort_direction", "desc"),
Name: c.Query("name"),
ApiKey: c.Query("api_key"),
}
prober, err := proberRepo.Probers(query)

View file

@ -2,6 +2,7 @@ package repo
import (
"fmt"
"slices"
"strings"
"github.com/ditatompel/xmr-nodes/internal/database"
@ -26,10 +27,13 @@ type Prober struct {
}
type ProbersQueryParams struct {
Name string
ApiKey string
RowsPerPage int
Page int
Name string
ApiKey string
RowsPerPage int
Page int
SortBy string
SortDirection string
}
type Probers struct {
@ -80,7 +84,17 @@ func (repo *ProberRepo) Probers(q ProbersQueryParams) (Probers, error) {
}
queryParams = append(queryParams, q.RowsPerPage, (q.Page-1)*q.RowsPerPage)
query := fmt.Sprintf("SELECT id, name, api_key, last_submit_ts FROM tbl_prober %s ORDER BY id DESC LIMIT ? OFFSET ?", where)
allowedSort := []string{"id", "last_submit_ts"}
sortBy := "id"
if slices.Contains(allowedSort, q.SortBy) {
sortBy = q.SortBy
}
sortDirection := "DESC"
if q.SortDirection == "asc" {
sortDirection = "ASC"
}
query := fmt.Sprintf("SELECT id, name, api_key, last_submit_ts FROM tbl_prober %s ORDER BY %s %s LIMIT ? OFFSET ?", where, sortBy, sortDirection)
row, err := repo.db.Query(query, queryParams...)
if err != nil {