返回 AiToEarn
create-pagination.ts
根目录 / project / aitoearn-electron / server / src / common / paginate / create-pagination.ts
1 /*
2 * @Author: nevin
3 * @Date: 2025-01-20 16:36:41
4 * @LastEditTime: 2025-02-22 17:43:47
5 * @LastEditors: nevin
6 * @Description:
7 */
8 import { Model } from 'mongoose';
9 import {
10 IPaginationMeta,
11 IPaginationOptions,
12 PaginationTypeEnum,
13 } from './interface';
14 import { Pagination } from './pagination';
15
16 const DEFAULT_LIMIT = 20;
17 const DEFAULT_PAGE = 1;
18
19 export function resolveOptions(
20 options: IPaginationOptions,
21 ): [number, number, PaginationTypeEnum] {
22 const { page, pageSize, paginationType } = options;
23
24 return [
25 page || DEFAULT_PAGE,
26 pageSize || DEFAULT_LIMIT,
27 paginationType || PaginationTypeEnum.TAKE_AND_SKIP,
28 ];
29 }
30
31 export function createPaginationObject<T>({
32 items,
33 totalItems,
34 currentPage,
35 limit,
36 }: {
37 items: T[];
38 totalItems?: number;
39 currentPage: number;
40 limit: number;
41 }): Pagination<T> {
42 const totalPages =
43 totalItems !== undefined ? Math.ceil(totalItems / limit) : undefined;
44
45 const meta: IPaginationMeta = {
46 totalItems,
47 itemCount: items.length,
48 itemsPerPage: +limit,
49 totalPages,
50 currentPage: +currentPage,
51 };
52
53 return new Pagination<T>(items, meta);
54 }
55
56 export async function paginateModel<T>(
57 model: Model<T>,
58 options: IPaginationOptions,
59 condition: any,
60 populate?: any,
61 sort?: any,
62 ): Promise<Pagination<T>> {
63 const [page, limit] = resolveOptions(options);
64
65 const promises: [Promise<T[]>, Promise<number> | undefined] = [
66 model
67 .find(condition)
68 .skip(limit * (page - 1))
69 .limit(limit)
70 .populate(populate)
71 .sort(sort),
72 model.countDocuments(condition),
73 ];
74
75 const [items, total] = await Promise.all(promises);
76
77 return createPaginationObject<T>({
78 items,
79 totalItems: total,
80 currentPage: page,
81 limit,
82 });
83 }
84
84 lines TYPESCRIPT