@longzai-intelligence/pagination 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.turbo/turbo-build.log +22 -0
  2. package/.turbo/turbo-lint.log +1 -0
  3. package/.turbo/turbo-test$colon$coverage.log +36 -0
  4. package/.turbo/turbo-test.log +14 -0
  5. package/.turbo/turbo-typecheck.log +4 -0
  6. package/CHANGELOG.md +11 -0
  7. package/README.md +218 -0
  8. package/coverage/base.css +224 -0
  9. package/coverage/block-navigation.js +87 -0
  10. package/coverage/coverage-final.json +12 -0
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +161 -0
  13. package/coverage/prettify.css +1 -0
  14. package/coverage/prettify.js +2 -0
  15. package/coverage/sort-arrow-sprite.png +0 -0
  16. package/coverage/sorter.js +210 -0
  17. package/coverage/src/adapters/index.html +131 -0
  18. package/coverage/src/adapters/index.ts.html +118 -0
  19. package/coverage/src/adapters/typeorm.adapter.ts.html +940 -0
  20. package/coverage/src/index.html +116 -0
  21. package/coverage/src/index.ts.html +253 -0
  22. package/coverage/src/types/index.html +176 -0
  23. package/coverage/src/types/index.ts.html +133 -0
  24. package/coverage/src/types/pagination.types.ts.html +292 -0
  25. package/coverage/src/types/result.types.ts.html +415 -0
  26. package/coverage/src/types/sort.types.ts.html +265 -0
  27. package/coverage/src/types/typeorm.d.ts.html +196 -0
  28. package/coverage/src/utils/index.html +146 -0
  29. package/coverage/src/utils/index.ts.html +178 -0
  30. package/coverage/src/utils/pagination.util.ts.html +703 -0
  31. package/coverage/src/utils/validation.util.ts.html +535 -0
  32. package/dist/index.cjs +1 -0
  33. package/dist/index.d.cts +117 -0
  34. package/dist/index.d.mts +117 -0
  35. package/dist/index.mjs +1 -0
  36. package/eslint.config.ts +3 -0
  37. package/package.json +62 -0
  38. package/src/__tests__/index.test.ts +66 -0
  39. package/src/__tests__/pagination.util.test.ts +253 -0
  40. package/src/__tests__/typeorm.adapter.test.ts +214 -0
  41. package/src/__tests__/validation.util.test.ts +122 -0
  42. package/src/adapters/index.ts +11 -0
  43. package/src/adapters/typeorm.adapter.ts +285 -0
  44. package/src/index.ts +56 -0
  45. package/src/types/index.ts +16 -0
  46. package/src/types/pagination.types.ts +69 -0
  47. package/src/types/result.types.ts +110 -0
  48. package/src/types/sort.types.ts +60 -0
  49. package/src/types/typeorm.d.ts +37 -0
  50. package/src/utils/index.ts +31 -0
  51. package/src/utils/pagination.util.ts +206 -0
  52. package/src/utils/validation.util.ts +150 -0
  53. package/tsconfig/.cache/app.tsbuildinfo +1 -0
  54. package/tsconfig/.cache/build.tsbuildinfo +1 -0
  55. package/tsconfig/.cache/node.tsbuildinfo +1 -0
  56. package/tsconfig/.cache/test.tsbuildinfo +1 -0
  57. package/tsconfig/app.json +12 -0
  58. package/tsconfig/node.json +11 -0
  59. package/tsconfig/test.json +14 -0
  60. package/tsconfig.json +9 -0
  61. package/tsdown.config.ts +6 -0
  62. package/vitest.config.ts +3 -0
@@ -0,0 +1,214 @@
1
+ /**
2
+ * @file typeorm.adapter.test.ts
3
+ * TypeORM 适配器测试
4
+ * @author Longzai Intelligence
5
+ */
6
+
7
+ import { describe, it, expect, vi } from 'vitest';
8
+ import {
9
+ paginateWithRepository,
10
+ paginateWithQueryBuilder,
11
+ createPaginationQueryBuilder,
12
+ } from '@/adapters/typeorm.adapter';
13
+ import type { Repository, SelectQueryBuilder, FindOptionsOrder } from 'typeorm';
14
+
15
+ /**
16
+ * 测试实体类型
17
+ *
18
+ * 用于测试的简单实体定义
19
+ */
20
+ type TestEntity = {
21
+ id: number;
22
+ name?: string;
23
+ status?: string;
24
+ createdAt?: Date;
25
+ };
26
+
27
+ /**
28
+ * 映射后的 DTO 类型
29
+ */
30
+ type MappedDto = {
31
+ mapped: TestEntity;
32
+ };
33
+
34
+ /**
35
+ * 创建模拟的 Repository
36
+ *
37
+ * @returns 模拟的 Repository 对象
38
+ */
39
+ function createMockRepository(): Repository<TestEntity> {
40
+ return {
41
+ findAndCount: vi.fn(),
42
+ createQueryBuilder: vi.fn(),
43
+ metadata: {
44
+ name: 'TestEntity',
45
+ },
46
+ } as Repository<TestEntity>;
47
+ }
48
+
49
+ /**
50
+ * 创建模拟的 QueryBuilder
51
+ *
52
+ * @returns 模拟的 QueryBuilder 对象
53
+ */
54
+ function createMockQueryBuilder(): SelectQueryBuilder<TestEntity> {
55
+ return {
56
+ skip: vi.fn().mockReturnThis(),
57
+ take: vi.fn().mockReturnThis(),
58
+ getManyAndCount: vi.fn(),
59
+ } as SelectQueryBuilder<TestEntity>;
60
+ }
61
+
62
+ describe('paginateWithRepository', () => {
63
+ it('应正确执行分页查询', async () => {
64
+ const mockRepository = createMockRepository();
65
+
66
+ const mockEntities: TestEntity[] = [{ id: 1 }, { id: 2 }];
67
+ vi.mocked(mockRepository.findAndCount).mockResolvedValue([mockEntities, 10]);
68
+
69
+ const result = await paginateWithRepository(mockRepository, { page: 1, pageSize: 10 });
70
+
71
+ expect(result).toEqual({
72
+ items: mockEntities,
73
+ total: 10,
74
+ page: 1,
75
+ pageSize: 10,
76
+ totalPages: 1,
77
+ hasNextPage: false,
78
+ hasPreviousPage: false,
79
+ });
80
+ });
81
+
82
+ it('应正确使用自定义映射函数', async () => {
83
+ const mockRepository = createMockRepository();
84
+
85
+ const mockEntities: TestEntity[] = [{ id: 1 }, { id: 2 }];
86
+ vi.mocked(mockRepository.findAndCount).mockResolvedValue([mockEntities, 10]);
87
+
88
+ const mapper = (entity: TestEntity): MappedDto => ({ mapped: entity });
89
+ const result = await paginateWithRepository(
90
+ mockRepository,
91
+ { page: 1, pageSize: 10 },
92
+ {
93
+ mapper,
94
+ },
95
+ );
96
+
97
+ expect(result.items).toEqual([{ mapped: { id: 1 } }, { mapped: { id: 2 } }]);
98
+ });
99
+
100
+ it('应正确处理分页参数', async () => {
101
+ const mockRepository = createMockRepository();
102
+
103
+ const mockEntities: TestEntity[] = [{ id: 1 }];
104
+ vi.mocked(mockRepository.findAndCount).mockResolvedValue([mockEntities, 100]);
105
+
106
+ const result = await paginateWithRepository(mockRepository, { page: 2, pageSize: 20 });
107
+
108
+ expect(result.page).toBe(2);
109
+ expect(result.pageSize).toBe(20);
110
+ expect(result.totalPages).toBe(5);
111
+ expect(result.hasNextPage).toBe(true);
112
+ expect(result.hasPreviousPage).toBe(true);
113
+ });
114
+
115
+ it('应正确使用查询选项', async () => {
116
+ const mockRepository = createMockRepository();
117
+
118
+ const mockEntities: TestEntity[] = [{ id: 1 }];
119
+ vi.mocked(mockRepository.findAndCount).mockResolvedValue([mockEntities, 10]);
120
+
121
+ const options = {
122
+ where: { status: 'active' },
123
+ order: { createdAt: 'DESC' } as FindOptionsOrder<TestEntity>,
124
+ relations: ['user'],
125
+ select: ['id', 'name'],
126
+ };
127
+
128
+ await paginateWithRepository(mockRepository, { page: 1, pageSize: 10 }, options);
129
+
130
+ expect(mockRepository.findAndCount).toHaveBeenCalledWith(
131
+ expect.objectContaining({
132
+ skip: 0,
133
+ take: 10,
134
+ where: options.where,
135
+ order: options.order,
136
+ relations: options.relations,
137
+ select: options.select,
138
+ }),
139
+ );
140
+ });
141
+ });
142
+
143
+ describe('paginateWithQueryBuilder', () => {
144
+ it('应正确执行分页查询', async () => {
145
+ const mockQueryBuilder = createMockQueryBuilder();
146
+
147
+ const mockEntities: TestEntity[] = [{ id: 1 }, { id: 2 }];
148
+ vi.mocked(mockQueryBuilder.getManyAndCount).mockResolvedValue([mockEntities, 10]);
149
+
150
+ const result = await paginateWithQueryBuilder(mockQueryBuilder, { page: 1, pageSize: 10 });
151
+
152
+ expect(result).toEqual({
153
+ items: mockEntities,
154
+ total: 10,
155
+ page: 1,
156
+ pageSize: 10,
157
+ totalPages: 1,
158
+ hasNextPage: false,
159
+ hasPreviousPage: false,
160
+ });
161
+ });
162
+
163
+ it('应正确使用自定义映射函数', async () => {
164
+ const mockQueryBuilder = createMockQueryBuilder();
165
+
166
+ const mockEntities: TestEntity[] = [{ id: 1 }, { id: 2 }];
167
+ vi.mocked(mockQueryBuilder.getManyAndCount).mockResolvedValue([mockEntities, 10]);
168
+
169
+ const mapper = (entity: TestEntity): MappedDto => ({ mapped: entity });
170
+ const result = await paginateWithQueryBuilder(
171
+ mockQueryBuilder,
172
+ { page: 1, pageSize: 10 },
173
+ mapper,
174
+ );
175
+
176
+ expect(result.items).toEqual([{ mapped: { id: 1 } }, { mapped: { id: 2 } }]);
177
+ });
178
+
179
+ it('应正确设置 skip 和 take', async () => {
180
+ const mockQueryBuilder = createMockQueryBuilder();
181
+
182
+ vi.mocked(mockQueryBuilder.getManyAndCount).mockResolvedValue([[], 0]);
183
+
184
+ await paginateWithQueryBuilder(mockQueryBuilder, { page: 2, pageSize: 20 });
185
+
186
+ expect(mockQueryBuilder.skip).toHaveBeenCalledWith(20);
187
+ expect(mockQueryBuilder.take).toHaveBeenCalledWith(20);
188
+ });
189
+ });
190
+
191
+ describe('createPaginationQueryBuilder', () => {
192
+ it('应正确创建 QueryBuilder', () => {
193
+ const mockQueryBuilder = createMockQueryBuilder();
194
+
195
+ const mockRepository = createMockRepository();
196
+ vi.mocked(mockRepository.createQueryBuilder).mockReturnValue(mockQueryBuilder);
197
+
198
+ const result = createPaginationQueryBuilder(mockRepository);
199
+
200
+ expect(result).toBe(mockQueryBuilder);
201
+ expect(mockRepository.createQueryBuilder).toHaveBeenCalled();
202
+ });
203
+
204
+ it('应使用自定义别名', () => {
205
+ const mockQueryBuilder = createMockQueryBuilder();
206
+
207
+ const mockRepository = createMockRepository();
208
+ vi.mocked(mockRepository.createQueryBuilder).mockReturnValue(mockQueryBuilder);
209
+
210
+ createPaginationQueryBuilder(mockRepository, 'custom_alias');
211
+
212
+ expect(mockRepository.createQueryBuilder).toHaveBeenCalledWith('custom_alias');
213
+ });
214
+ });
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @file validation.util.test.ts
3
+ * 分页参数验证工具函数测试
4
+ * @author Longzai Intelligence
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ isValidPage,
10
+ isValidPageSize,
11
+ isValidOffset,
12
+ isValidLimit,
13
+ isValidPagination,
14
+ isValidOffsetPagination,
15
+ } from '@/utils/validation.util';
16
+ import { PAGINATION_DEFAULTS } from '@/types';
17
+
18
+ describe('isValidPage', () => {
19
+ it('应返回 true 对于有效的页码', () => {
20
+ expect(isValidPage(1)).toBe(true);
21
+ expect(isValidPage(10)).toBe(true);
22
+ expect(isValidPage(1000)).toBe(true);
23
+ });
24
+
25
+ it('应返回 false 对于无效的页码', () => {
26
+ expect(isValidPage(0)).toBe(false);
27
+ expect(isValidPage(-1)).toBe(false);
28
+ expect(isValidPage(1.5)).toBe(false);
29
+ expect(isValidPage('1')).toBe(false);
30
+ expect(isValidPage(null)).toBe(false);
31
+ expect(isValidPage(undefined)).toBe(false);
32
+ expect(isValidPage(NaN)).toBe(false);
33
+ });
34
+ });
35
+
36
+ describe('isValidPageSize', () => {
37
+ it('应返回 true 对于有效的页面大小', () => {
38
+ expect(isValidPageSize(1)).toBe(true);
39
+ expect(isValidPageSize(20)).toBe(true);
40
+ expect(isValidPageSize(PAGINATION_DEFAULTS.maxPageSize)).toBe(true);
41
+ });
42
+
43
+ it('应返回 false 对于无效的页面大小', () => {
44
+ expect(isValidPageSize(0)).toBe(false);
45
+ expect(isValidPageSize(-1)).toBe(false);
46
+ expect(isValidPageSize(PAGINATION_DEFAULTS.maxPageSize + 1)).toBe(false);
47
+ expect(isValidPageSize(1.5)).toBe(false);
48
+ expect(isValidPageSize('20')).toBe(false);
49
+ expect(isValidPageSize(null)).toBe(false);
50
+ expect(isValidPageSize(undefined)).toBe(false);
51
+ });
52
+ });
53
+
54
+ describe('isValidOffset', () => {
55
+ it('应返回 true 对于有效的偏移量', () => {
56
+ expect(isValidOffset(0)).toBe(true);
57
+ expect(isValidOffset(10)).toBe(true);
58
+ expect(isValidOffset(1000)).toBe(true);
59
+ });
60
+
61
+ it('应返回 false 对于无效的偏移量', () => {
62
+ expect(isValidOffset(-1)).toBe(false);
63
+ expect(isValidOffset(1.5)).toBe(false);
64
+ expect(isValidOffset('10')).toBe(false);
65
+ expect(isValidOffset(null)).toBe(false);
66
+ expect(isValidOffset(undefined)).toBe(false);
67
+ });
68
+ });
69
+
70
+ describe('isValidLimit', () => {
71
+ it('应返回 true 对于有效的限制数量', () => {
72
+ expect(isValidLimit(1)).toBe(true);
73
+ expect(isValidLimit(20)).toBe(true);
74
+ expect(isValidLimit(PAGINATION_DEFAULTS.maxPageSize)).toBe(true);
75
+ });
76
+
77
+ it('应返回 false 对于无效的限制数量', () => {
78
+ expect(isValidLimit(0)).toBe(false);
79
+ expect(isValidLimit(-1)).toBe(false);
80
+ expect(isValidLimit(PAGINATION_DEFAULTS.maxPageSize + 1)).toBe(false);
81
+ expect(isValidLimit(1.5)).toBe(false);
82
+ expect(isValidLimit('20')).toBe(false);
83
+ expect(isValidLimit(null)).toBe(false);
84
+ expect(isValidLimit(undefined)).toBe(false);
85
+ });
86
+ });
87
+
88
+ describe('isValidPagination', () => {
89
+ it('应返回 true 对于有效的分页参数', () => {
90
+ expect(isValidPagination({ page: 1, pageSize: 20 })).toBe(true);
91
+ expect(isValidPagination({ page: 5 })).toBe(true);
92
+ expect(isValidPagination({ pageSize: 50 })).toBe(true);
93
+ expect(isValidPagination({})).toBe(true);
94
+ });
95
+
96
+ it('应返回 false 对于无效的分页参数', () => {
97
+ expect(isValidPagination(null)).toBe(false);
98
+ expect(isValidPagination('string')).toBe(false);
99
+ expect(isValidPagination(123)).toBe(false);
100
+ expect(isValidPagination({ page: -1 })).toBe(false);
101
+ expect(isValidPagination({ pageSize: 0 })).toBe(false);
102
+ expect(isValidPagination({ page: 1.5 })).toBe(false);
103
+ });
104
+ });
105
+
106
+ describe('isValidOffsetPagination', () => {
107
+ it('应返回 true 对于有效的 offset 分页参数', () => {
108
+ expect(isValidOffsetPagination({ limit: 20, offset: 0 })).toBe(true);
109
+ expect(isValidOffsetPagination({ limit: 50 })).toBe(true);
110
+ expect(isValidOffsetPagination({ offset: 100 })).toBe(true);
111
+ expect(isValidOffsetPagination({})).toBe(true);
112
+ });
113
+
114
+ it('应返回 false 对于无效的 offset 分页参数', () => {
115
+ expect(isValidOffsetPagination(null)).toBe(false);
116
+ expect(isValidOffsetPagination('string')).toBe(false);
117
+ expect(isValidOffsetPagination(123)).toBe(false);
118
+ expect(isValidOffsetPagination({ offset: -1 })).toBe(false);
119
+ expect(isValidOffsetPagination({ limit: 0 })).toBe(false);
120
+ expect(isValidOffsetPagination({ limit: 1.5 })).toBe(false);
121
+ });
122
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 适配器导出入口
3
+ */
4
+
5
+ export type { EntityMapper, TypeOrmPaginateOptions } from './typeorm.adapter';
6
+
7
+ export {
8
+ paginateWithRepository,
9
+ paginateWithQueryBuilder,
10
+ createPaginationQueryBuilder,
11
+ } from './typeorm.adapter';
@@ -0,0 +1,285 @@
1
+ /**
2
+ * TypeORM 分页适配器
3
+ *
4
+ * 注意:此模块需要安装 typeorm 作为 peerDependency
5
+ */
6
+
7
+ import type {
8
+ Repository,
9
+ SelectQueryBuilder,
10
+ ObjectLiteral,
11
+ FindManyOptions,
12
+ FindOptionsOrder,
13
+ } from 'typeorm';
14
+ import type { PaginationParams, PaginatedResult } from '../types';
15
+ import {
16
+ normalizePagination,
17
+ calculateOffset,
18
+ calculateTotalPages,
19
+ hasNextPage,
20
+ hasPreviousPage,
21
+ } from '../utils';
22
+
23
+ /**
24
+ * 实体映射器函数类型
25
+ *
26
+ * 将实体类型转换为 DTO 类型的映射函数
27
+ *
28
+ * @typeParam TEntity - 实体类型
29
+ * @typeParam TDto - DTO 类型
30
+ */
31
+ export type EntityMapper<TEntity, TDto> = (entity: TEntity) => TDto | Promise<TDto>;
32
+
33
+ /**
34
+ * TypeORM 分页查询选项(带映射器)
35
+ *
36
+ * 配置 TypeORM 分页查询的选项,必须提供映射函数
37
+ *
38
+ * @typeParam TEntity - 实体类型
39
+ * @typeParam TDto - DTO 类型
40
+ */
41
+ export type TypeOrmPaginateOptionsWithMapper<TEntity extends ObjectLiteral, TDto> = {
42
+ /**
43
+ * 实体到 DTO 的映射函数
44
+ *
45
+ * 必须提供映射函数以确保类型安全
46
+ */
47
+ mapper: EntityMapper<TEntity, TDto>;
48
+
49
+ /**
50
+ * 排序规则
51
+ */
52
+ order?: FindOptionsOrder<TEntity>;
53
+
54
+ /**
55
+ * 查询条件
56
+ */
57
+ where?: FindManyOptions<TEntity>['where'];
58
+
59
+ /**
60
+ * 关联关系
61
+ */
62
+ relations?: FindManyOptions<TEntity>['relations'];
63
+
64
+ /**
65
+ * 选择字段
66
+ */
67
+ select?: FindManyOptions<TEntity>['select'];
68
+ };
69
+
70
+ /**
71
+ * TypeORM 分页查询选项(无映射器)
72
+ *
73
+ * 配置 TypeORM 分页查询的选项,返回原始实体
74
+ *
75
+ * @typeParam TEntity - 实体类型
76
+ */
77
+ export type TypeOrmPaginateOptionsNoMapper<TEntity extends ObjectLiteral> = {
78
+ /**
79
+ * 排序规则
80
+ */
81
+ order?: FindOptionsOrder<TEntity>;
82
+
83
+ /**
84
+ * 查询条件
85
+ */
86
+ where?: FindManyOptions<TEntity>['where'];
87
+
88
+ /**
89
+ * 关联关系
90
+ */
91
+ relations?: FindManyOptions<TEntity>['relations'];
92
+
93
+ /**
94
+ * 选择字段
95
+ */
96
+ select?: FindManyOptions<TEntity>['select'];
97
+ };
98
+
99
+ /**
100
+ * TypeORM 分页查询选项
101
+ *
102
+ * 配置 TypeORM 分页查询的选项
103
+ *
104
+ * @typeParam TEntity - 实体类型
105
+ * @typeParam TDto - DTO 类型
106
+ */
107
+ export type TypeOrmPaginateOptions<TEntity extends ObjectLiteral, TDto = TEntity> =
108
+ | TypeOrmPaginateOptionsWithMapper<TEntity, TDto>
109
+ | TypeOrmPaginateOptionsNoMapper<TEntity>;
110
+
111
+ /**
112
+ * 类型守卫:检查选项是否包含映射器
113
+ *
114
+ * @typeParam TEntity - 实体类型
115
+ * @typeParam TDto - DTO 类型
116
+ * @param options - 查询选项
117
+ * @returns 是否包含映射器
118
+ */
119
+ function hasMapper<TEntity extends ObjectLiteral, TDto>(
120
+ options:
121
+ | TypeOrmPaginateOptionsWithMapper<TEntity, TDto>
122
+ | TypeOrmPaginateOptionsNoMapper<TEntity>
123
+ | undefined,
124
+ ): options is TypeOrmPaginateOptionsWithMapper<TEntity, TDto> {
125
+ return options !== undefined && 'mapper' in options;
126
+ }
127
+
128
+ /**
129
+ * 构建分页结果
130
+ *
131
+ * 内部辅助函数,构建分页结果对象
132
+ *
133
+ * @typeParam TDto - DTO 类型
134
+ * @param items - 数据项数组
135
+ * @param total - 总数
136
+ * @param page - 当前页
137
+ * @param pageSize - 每页大小
138
+ * @returns 分页结果
139
+ */
140
+ function buildPaginatedResult<TDto>(
141
+ items: TDto[],
142
+ total: number,
143
+ page: number,
144
+ pageSize: number,
145
+ ): PaginatedResult<TDto> {
146
+ /**
147
+ * 计算得到的总页数
148
+ */
149
+ const totalPages = calculateTotalPages(total, pageSize);
150
+ return {
151
+ items,
152
+ total,
153
+ page,
154
+ pageSize,
155
+ totalPages,
156
+ hasNextPage: hasNextPage(page, totalPages),
157
+ hasPreviousPage: hasPreviousPage(page),
158
+ };
159
+ }
160
+
161
+ /**
162
+ * 使用 Repository 进行分页查询
163
+ *
164
+ * 通过 TypeORM Repository 进行分页查询,支持实体到 DTO 的映射
165
+ *
166
+ * 当提供 mapper 时返回映射后的 DTO,否则返回原始实体
167
+ *
168
+ * @typeParam TEntity - 实体类型
169
+ * @typeParam TDto - DTO 类型
170
+ * @param repository - TypeORM 仓库
171
+ * @param params - 分页参数
172
+ * @param options - 查询选项
173
+ * @returns 分页结果
174
+ */
175
+ export async function paginateWithRepository<TEntity extends ObjectLiteral, TDto = TEntity>(
176
+ repository: Repository<TEntity>,
177
+ params: PaginationParams,
178
+ options?: TypeOrmPaginateOptions<TEntity, TDto>,
179
+ ): Promise<PaginatedResult<TEntity | TDto>> {
180
+ /**
181
+ * 规范化后的分页参数
182
+ */
183
+ const { page, pageSize } = normalizePagination(params);
184
+
185
+ /**
186
+ * 计算得到的偏移量
187
+ */
188
+ const offset = calculateOffset(page, pageSize);
189
+
190
+ /**
191
+ * 默认排序规则
192
+ */
193
+ const defaultOrder: FindOptionsOrder<TEntity> = { createdAt: 'DESC' };
194
+
195
+ /**
196
+ * TypeORM 查询选项配置
197
+ */
198
+ const findOptions: FindManyOptions<TEntity> = {
199
+ skip: offset,
200
+ take: pageSize,
201
+ where: options?.where,
202
+ relations: options?.relations,
203
+ select: options?.select,
204
+ order: options?.order ?? defaultOrder,
205
+ };
206
+
207
+ /**
208
+ * 查询结果:实体数组和总数
209
+ */
210
+ const [entities, total] = await repository.findAndCount(findOptions);
211
+
212
+ if (hasMapper(options)) {
213
+ /**
214
+ * 映射后的 DTO 数组
215
+ */
216
+ const items = await Promise.all(entities.map(options.mapper));
217
+ return buildPaginatedResult(items, total, page, pageSize);
218
+ }
219
+
220
+ return buildPaginatedResult(entities, total, page, pageSize);
221
+ }
222
+
223
+ /**
224
+ * 使用 QueryBuilder 进行分页查询
225
+ *
226
+ * 通过 TypeORM QueryBuilder 进行分页查询,支持实体到 DTO 的映射
227
+ *
228
+ * 当提供 mapper 时返回映射后的 DTO,否则返回原始实体
229
+ *
230
+ * @typeParam TEntity - 实体类型
231
+ * @typeParam TDto - DTO 类型
232
+ * @param queryBuilder - TypeORM QueryBuilder
233
+ * @param params - 分页参数
234
+ * @param mapper - 实体到 DTO 的映射函数(可选)
235
+ * @returns 分页结果
236
+ */
237
+ export async function paginateWithQueryBuilder<TEntity extends ObjectLiteral, TDto = TEntity>(
238
+ queryBuilder: SelectQueryBuilder<TEntity>,
239
+ params: PaginationParams,
240
+ mapper?: EntityMapper<TEntity, TDto>,
241
+ ): Promise<PaginatedResult<TEntity | TDto>> {
242
+ /**
243
+ * 规范化后的分页参数
244
+ */
245
+ const { page, pageSize } = normalizePagination(params);
246
+
247
+ /**
248
+ * 计算得到的偏移量
249
+ */
250
+ const offset = calculateOffset(page, pageSize);
251
+
252
+ queryBuilder.skip(offset).take(pageSize);
253
+
254
+ /**
255
+ * 查询结果:实体数组和总数
256
+ */
257
+ const [entities, total] = await queryBuilder.getManyAndCount();
258
+
259
+ if (mapper) {
260
+ /**
261
+ * 映射后的 DTO 数组
262
+ */
263
+ const items = await Promise.all(entities.map(mapper));
264
+ return buildPaginatedResult(items, total, page, pageSize);
265
+ }
266
+
267
+ return buildPaginatedResult(entities, total, page, pageSize);
268
+ }
269
+
270
+ /**
271
+ * 创建分页查询构建器
272
+ *
273
+ * 创建一个用于分页查询的 TypeORM QueryBuilder
274
+ *
275
+ * @typeParam TEntity - 实体类型
276
+ * @param repository - TypeORM 仓库
277
+ * @param alias - 查询别名
278
+ * @returns QueryBuilder
279
+ */
280
+ export function createPaginationQueryBuilder<TEntity extends ObjectLiteral>(
281
+ repository: Repository<TEntity>,
282
+ alias?: string,
283
+ ): SelectQueryBuilder<TEntity> {
284
+ return repository.createQueryBuilder(alias ?? repository.metadata.name.toLowerCase());
285
+ }
package/src/index.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 分页包主入口
3
+ */
4
+
5
+ // 类型导出
6
+ export type {
7
+ PaginationParams,
8
+ OffsetPaginationParams,
9
+ CursorPaginationParams,
10
+ PaginationDefaults,
11
+ } from './types';
12
+
13
+ export type { PaginatedResult, OffsetPaginatedResult, CursorPaginatedResult } from './types';
14
+
15
+ export type { SortOrder, SortParams, SortItem, MultiSortParams } from './types';
16
+
17
+ // 常量导出
18
+ export { PAGINATION_DEFAULTS } from './types';
19
+
20
+ // 工具函数导出
21
+ export type {
22
+ OffsetPaginationResult,
23
+ PagePaginationResult,
24
+ PaginationValidationResult,
25
+ OffsetPaginationValidationResult,
26
+ } from './utils';
27
+
28
+ export {
29
+ normalizePagination,
30
+ normalizeOffsetPagination,
31
+ calculateOffset,
32
+ calculateTotalPages,
33
+ hasNextPage,
34
+ hasPreviousPage,
35
+ offsetToPage,
36
+ pageToOffset,
37
+ createPaginatedResult,
38
+ } from './utils';
39
+
40
+ export {
41
+ isValidPage,
42
+ isValidPageSize,
43
+ isValidOffset,
44
+ isValidLimit,
45
+ isValidPagination,
46
+ isValidOffsetPagination,
47
+ } from './utils';
48
+
49
+ // 适配器导出
50
+ export type { EntityMapper, TypeOrmPaginateOptions } from './adapters';
51
+
52
+ export {
53
+ paginateWithRepository,
54
+ paginateWithQueryBuilder,
55
+ createPaginationQueryBuilder,
56
+ } from './adapters';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 类型导出入口
3
+ */
4
+
5
+ export type {
6
+ PaginationParams,
7
+ OffsetPaginationParams,
8
+ CursorPaginationParams,
9
+ PaginationDefaults,
10
+ } from './pagination.types';
11
+
12
+ export { PAGINATION_DEFAULTS } from './pagination.types';
13
+
14
+ export type { PaginatedResult, OffsetPaginatedResult, CursorPaginatedResult } from './result.types';
15
+
16
+ export type { SortOrder, SortParams, SortItem, MultiSortParams } from './sort.types';