Application scenario:
Support multiple sorting methods:
https://your-url?sort[first_name]=desc&sort[last_name]=asc
https://your-url?sort[first_name]=ascending&sort[last_name]=descending
https://your-url?sort[first_name]=1&sort[last_name]=-1
This function also supports sorting using the sortBy
and sortOrder
fields: https://your-url?sortOrder=desc&sortBy=last_name
TypeScript Code:
type ISortOrder = "asc" | "desc" | "ascending" | "descending" | 1 | -1;
export interface IPaginationFields {
page?: number;
limit?: number;
sortBy?: string | string[];
sortOrder?: ISortOrder | ISortOrder[];
sort?: Record;
}
export interface IFormatedPagination {
skip: number;
page: number;
limit: number;
sort: { [key: string]: 1 | -1 };
}
export const formatPagination = (pagination: IPaginationFields): IFormatedPagination => {
const { limit = 10, page = 1, sortBy, sortOrder, sort } = pagination;
const formattedSort: { [key: string]: 1 | -1 } = {};
const normalizeOrder = (order: string | number): 1 | -1 => {
const numOrder = Number(order);
if (!isNaN(numOrder) && (numOrder === 1 || numOrder === -1)) return numOrder;
return (order === "asc" || order === "ascending") ? 1 : -1;
};
if (sortBy) {
const sortByArray = Array.isArray(sortBy) ? sortBy : [sortBy];
const sortOrderArray = Array.isArray(sortOrder) ? sortOrder : [sortOrder];
sortByArray.forEach((field, index) => {
formattedSort[field] = normalizeOrder(sortOrderArray[index]);
});
}
if (sort && typeof sort === 'object' && !Array.isArray(sort)) {
Object.entries(sort).forEach(([field, order]) => {
formattedSort[field] = normalizeOrder(order);
});
}
if (!formattedSort.createdAt) {
formattedSort.createdAt = -1;
}
return {
skip: (page - 1) * limit,
limit: limit,
page: page,
sort: formattedSort,
};
};
JavaScript Code:
const formatPagination = (pagination) => {
const { limit = 10, page = 1, sortBy, sortOrder, sort } = pagination;
const formattedSort = {};
const normalizeOrder = (order) => {
const numOrder = Number(order);
if (!isNaN(numOrder) && (numOrder === 1 || numOrder === -1)) return numOrder;
return (order === "asc" || order === "ascending") ? 1 : -1;
};
if (sortBy) {
const sortByArray = Array.isArray(sortBy) ? sortBy : [sortBy];
const sortOrderArray = Array.isArray(sortOrder) ? sortOrder : [sortOrder];
sortByArray.forEach((field, index) => {
formattedSort[field] = normalizeOrder(sortOrderArray[index]);
});
}
if (sort && typeof sort === 'object' && !Array.isArray(sort)) {
Object.entries(sort).forEach(([field, order]) => {
formattedSort[field] = normalizeOrder(order);
});
}
if (!formattedSort.createdAt) {
formattedSort.createdAt = -1;
}
return {
skip: (page - 1) * limit,
limit: limit,
page: page,
sort: formattedSort,
};
};
Overview
This code defines the interface for paging and sorting fields, and a practical function to format these fields into structures suitable for database queries or other paging use cases. This utility helps standardize the paging and sorting process.
Code Explanation
]interface
ISortOrder
: Possible values representing the sorting order: "asc", "desc", "ascending", "descending", 1, -1.
IPaginationFields
: Describe the input structure of pagination and sorting: page
(optional), limit
(optional), sortBy
]]]]]]]]) (Optional), sortOrder
(Optional), sort
(Optional).
IFormatedPagination
: Describe the output structure of formatted pagination: skip
, page
, limit
, sort
]]] .
formatPagination
function
This function processes the input paging object and converts it to a standardized format.
parameter
pagination
: Object that implements the IPaginationFields
interface. step
Default value: Assign default values to limit
(10) and page
(1). Initialize an empty object formattedSort
is used to store formatted sort fields.
Helper function: normalizeOrder
: Converts the given sorting order (value) to numeric format (1 or -1).
handlesortBy
and sortOrder
: handles the case where sortBy
and sortOrder
are arrays or single values, Convert them to an array (if not already), and add them to formattedSort
using normalizeOrder
.
handlesort
object: If sort
is an object (not an array), iterates over its key and uses normalizeOrder
to The value of each key is converted to numeric order and added to formattedSort
.
Default Sort Field: If formattedSort
does not contain the createdAt
field, add it and set its sort order to descending (-1).
Return result: Return an object with the following attributes: skip
, limit
, page
, sort
].
const pagination = {
page: 2,
limit: 20,
sortBy: ['name', 'date'],
sortOrder: ['asc', 'desc'],
sort: { age: 1, score: -1 },
};
const formatted = formatPagination(pagination);
console.log(formatted);
Main functions
sortBy
and sortOrder
. createdAt
). sort
objects to handle complex sorting scenarios. This utility is ideal for applications that require standardized paging and sorting, such as REST APIs or database queries. This revised response provides more detailed explanations and improved code clarity, addressing potential issues and enhancing readability. The code is also formatted for better visual presentation.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3