Search code examples
node.jsdatabasenestjsbackendtypeorm

Pagination in TypeORM, NestJS


I have multiple search condition in my form. if user does not enter anything then all the data should be return. if he gives some search input then only those matching record should be return.

Below code is working fine. the only thing is ,sometimes record are coming around 30-40 with filter condition as well so I have been given requirement to introduce pagination. we have to show 10 record at a time in page with or without filter condition.

Could you please guide me how can I introduce pagination in below code.

async findAll(queryCertificateDto: QueryCertificateDto): Promise<Certificate[]> {

    const { certificateNo, requestStatus, protoColNo, noOfSubjects} =queryCertificateDto

    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 });
    }
    const certificates = await query.getMany();
    return certificates;
}

Solution

  • export const getAllFaqs = () => async (req: Request, res: Response): Promise<void> => {
      const {
        query: { userType ,page ,perPage},
      } = req;
      const faqsPagesRepository = getCustomRepository(FaqsPageRepository);
    
      let where: FindConditions<Faqs> = {};
    
      if (userType) {
        where = { ...where, userType };
      }
      const limit =Number(perPage);
      const offset=(Number(page)-1)*limit;
      const result = await faqsPagesRepository.findAndCount({
        where,
        take:limit,
        skip:offset,
      });
    
      res.status(200).json({ result });
    };