NestJS+TypeORM多条件查询场景下如何实现分页功能
实现分页功能的修改步骤
- 第一步:修改
QueryCertificateDto,新增分页参数并设置默认值,避免前端未传参时出错
export class QueryCertificateDto { // 原有查询字段保持不变 certificateNo?: string; requestStatus?: string; protoColNo?: string; noOfSubjects?: number; // 新增分页字段,设置默认值:默认第1页,每页10条 page?: number = 1; pageSize?: number = 10; }
- 第二步:调整
findAll方法逻辑,加入分页计算,可同时返回分页元信息方便前端渲染分页组件
// 可单独抽为通用分页返回类型,也可直接写在方法返回定义中 type PaginatedResult<T> = { list: T[]; total: number; // 符合条件的总记录数 currentPage: number; pageSize: number; totalPages: number; // 总页数 } async findAll(queryCertificateDto: QueryCertificateDto): Promise<PaginatedResult<Certificate>> { // 解构出新增的分页参数 const { certificateNo, requestStatus, protoColNo, noOfSubjects, page, pageSize } = queryCertificateDto; // 计算偏移量:页码从1开始,所以要减1再乘每页数量 const skip = (page - 1) * pageSize; const query = this.certificateRepository.createQueryBuilder('certificate'); // 原有过滤逻辑完全保留,不影响多条件查询功能 if (certificateNo) { query.andWhere('certificate.certificateNo=:certificateNo', { certificateNo }); } if (requestStatus) { query.andWhere('certificate.requestStatus=:requestStatus', { requestStatus }); } if (protoColNo) { query.andWhere('certificate.protoColNo=:protoColNo', { protoColNo }); } if (noOfSubjects) { query.andWhere('certificate.noOfSubjects=:noOfSubjects', { noOfSubjects }); } // 插入分页参数 query.skip(skip).take(pageSize); // 同时查询当前页数据和符合条件的总记录数 const [certificates, total] = await query.getManyAndCount(); // 计算总页数 const totalPages = Math.ceil(total / pageSize); return { list: certificates, total, currentPage: page, pageSize, totalPages }; }
- 可选简化方案:如果不需要返回分页元信息,仅需要返回当前页数据,可不用修改返回类型,仅在原有query逻辑后添加
query.skip((page - 1) * pageSize).take(pageSize),最后调用getMany()返回即可 - 补充优化建议:可根据业务需要对page、pageSize参数做合法性校验,比如限制page最小为1、pageSize最大不超过50,避免恶意请求拉取全量数据
内容的提问来源于stack exchange,提问作者Shruti sharma
相关产品推荐
相关产品推荐

