Advertisement
simonedare_

Pagination backend

Feb 21st, 2024
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async handleGetExercise(
  2.     user: UserDTO,
  3.     queryOptions: ExerciseQueryOptionsDTO,
  4.   ): Promise<any> {
  5.     try {
  6.       const businessEntry = user.business;
  7.       if (!businessEntry) {
  8.         return await handleSendNotFound('Business not found');
  9.       }
  10.       const limit = parseInt(queryOptions.limit?.toString() ?? '10');
  11.       const page = parseInt(queryOptions.page?.toString() ?? '1');
  12.       const types = queryOptions.type?.split(',') ?? '';
  13.       const query = queryOptions.query ?? '';
  14.  
  15.       const skip = limit * page - limit;
  16.  
  17.       const [exercises, count] = await this.exerciseRepository
  18.         .createQueryBuilder('exercise')
  19.         .select()
  20.         .where('LOWER(exercise.title) like :title', {
  21.           title: `%${query.toLowerCase()}%`,
  22.         })
  23.         .andWhere(
  24.           types.length > 0 && types[0] != ''
  25.             ? 'exercise.muscleGroup && (:...types)'
  26.             : '1=1',
  27.           { types: [types] },
  28.         )
  29.         .andWhere('exercise.businessId = :bid', { bid: businessEntry.id })
  30.         .orderBy('exercise.createdAt')
  31.         .skip(skip)
  32.         .take(limit)
  33.         .getManyAndCount();
  34.  
  35.       return await handleSendData('Retrieved exercises', {
  36.         exercises,
  37.         count,
  38.         hasMore: limit * page < count,
  39.       });
  40.     } catch (e) {
  41.       return await handleSendFallbackError(
  42.         e,
  43.         'Database: Failed to retrieve exercises!',
  44.       );
  45.     }
  46.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement