Skip to content

Commit af28ec0

Browse files
committed
feat(utils): add get pagination params
1 parent 22d71fd commit af28ec0

2 files changed

Lines changed: 66 additions & 1 deletion

File tree

src/types/api-response.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,39 @@ export interface StreamResponse {
179179
/** Chunk size in bytes */
180180
chunkSize: number;
181181
}
182+
183+
/**
184+
* Sort direction enumeration.
185+
*/
186+
export enum SortDirection {
187+
/** Ascending sort order */
188+
ASC = 'asc',
189+
190+
/** Descending sort order */
191+
DESC = 'desc'
192+
}
193+
194+
/**
195+
* Pagination parameters for API requests.
196+
*/
197+
export interface PaginationParams {
198+
/** Current page number (1-based index) */
199+
page: number;
200+
201+
/** Number of records per page */
202+
limit: number;
203+
204+
/** Field by which the data is sorted */
205+
sortBy: string;
206+
207+
/** Sort order: ascending or descending */
208+
sortOrder: SortDirection;
209+
210+
/** Optional search query */
211+
search?: string;
212+
}
213+
214+
/**
215+
* Type that combines pagination parameters with additional data.
216+
*/
217+
export type WithPagination<T = {}> = PaginationParams & T;

src/utils/request.utils.ts

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
* SOFTWARE.
2323
*/
2424

25+
import { Request } from 'express';
26+
import { SortDirection, WithPagination } from '../types/api-response';
27+
2528
/**
2629
* Options for parsing and validating request parameters.
2730
*/
@@ -53,6 +56,32 @@ export interface ValidationResult<T> {
5356
error?: string;
5457
}
5558

59+
/**
60+
* Extracts pagination, sorting, and optional search params from a request.
61+
*
62+
* @param req - Express request
63+
* @returns Object containing validated pagination, sorting, and additional query params
64+
*/
65+
export const getPaginationParams = <T = {}>(req: Request): WithPagination<T> => {
66+
const query = req.query as Record<string, string | string[]>;
67+
68+
// Extract page & limit
69+
const { page, limit } = extractPaginationParams(query, 1, 20, 100);
70+
const { sortBy, sortOrder } = extractSortParams(query, []);
71+
72+
// Optional search param
73+
const search = typeof query.search === 'string' ? query.search : undefined;
74+
75+
return {
76+
...(query as T),
77+
page,
78+
limit,
79+
sortBy,
80+
sortOrder: sortOrder as SortDirection,
81+
search
82+
};
83+
};
84+
5685
/**
5786
* Safely parses a string parameter to a number.
5887
*
@@ -199,7 +228,7 @@ export function extractSortParams(
199228
}
200229

201230
// Validate field
202-
if (!allowedFields.includes(sortBy)) {
231+
if (allowedFields.length && !allowedFields.includes(sortBy)) {
203232
sortBy = defaultSort.sortBy;
204233
}
205234

0 commit comments

Comments
 (0)