javascript 使用过滤器和分页获取所有元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用过滤器和分页获取所有元素相关的知识,希望对你有一定的参考价值。

/**
 * @name getAllArticles
 */
controller.getAllArticles = async (req, res, next) => {
	// Extracting Information from req.query
	// page = current page number
	// range = from which number to which number
	// sort = sort by which property and asc or des
	const page = req.query.page ? parseInt(req.query.page) : 1;
	const queryRange = req.query.range
		? extractQueryArray(req.query.range)
		: false;
	const querySort = req.query.sort
		? extractQueryArray(req.query.sort)
		: false;
	const queryFilter = req.query.filter
		? extractQueryArray(req.query.filter)
		: false;

	// creating range and limit
	let rangeStart = 0;
	let rangeEnd = 10;

	if (queryRange) {
		rangeStart = parseInt(queryRange[0]);
		rangeEnd = parseInt(queryRange[1]);
	}

	const limit = Math.abs(rangeEnd - rangeStart);

	// creating sorted type and sorted property
	let sortedBy = 'createdAt';
	let sortType = 'asc';

	if (querySort) {
		sortedBy = querySort[0];
		sortType = querySort[1];
	}

	if (sortType.toLowerCase() === 'des') {
		sortedBy = '-' + sortedBy;
	}

	// creating filter object
	let filter = {};
	if (queryFilter) {
		filter[queryFilter[0]] = queryFilter[1];
	}

	// database query and pagination
	try {
		const articles = await Article.find(filter)
			.sort(sortedBy)
			.skip(page * limit - limit)
			.limit(limit);

		const totalArticles = await Article.countDocuments(filter);
		const totalPage = Math.ceil(totalArticles / limit);
		const message = `Total ${totalArticles} ${
			totalArticles > 1 ? 'Articles' : 'Article'
		} Founds`;

		logger.info(message);

		// sending response
		return res.status(200).json({
			message,
			page,
			rangeStart,
			rangeEnd,
			limit,
			totalPage,
			sortedBy,
			sortType,
			totalArticles,
			articles
		});
	} catch (e) {
		next(e);
	}
};

/**
 * @name extractQueryArray
 * @param str string
 * @description input query string and return formatted array
 */
function extractQueryArray(str) {
	const result = str.match(/['"](.*?)['"]/gm);
	result[0] = result[0].replace(/'/g, '');
	result[1] = result[1].replace(/'/g, '');

	return result;
}

以上是关于javascript 使用过滤器和分页获取所有元素的主要内容,如果未能解决你的问题,请参考以下文章

过滤和分页不适用于 ngxpagination 模板

如何使用过滤器和分页优化 SQL Server 查询?

Tablesorter 过滤器小部件,Tablesorter-filter 和分页问题

数据表 - 自定义过滤器和分页

为服务器端过滤和分页构建 Angular 应用程序

使用服务器端时搜索和分页不起作用